Python | 5 python questions

Question 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Parent(object):
x = 1

class Child1(Parent):
pass

class Child2(Parent):
pass

print Parent.x, Child1.x, Child2.x
>>> 1 1 1

Child1.x = 2
print Parent.x, Child1.x, Child2.x
>>> 1 2 1

Parent.x = 3
print Parent.x, Child1.x, Child2.x
>>> 3 2 3

Question 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def div1(x,y):
print("%s/%s = %s" % (x, y, x/y))

def div2(x,y):
print("%s//%s = %s" % (x, y, x//y))

# Based on python2
div1(5,2)
>>> 5 / 2 = 2 # returns 2.5 in python3

div1(5.,2)
>>> 5. / 2 = 2.5

div2(5,2)
>>> 5 // 2 = 2

div2(5.,2.)
>>> 5 // 2 = 2.0

Note: In python3 / returns floats, while // returns int

Question 3

1
2
3
4
list = ['a', 'b', 'c', 'd', 'e']
print list[10:]

>>> [] # Isn't a None?.?

Question 4

1
2
3
4
5
6
def multipliers():
return [lambda x : i * x for i in range(4)]

print [m(2) for m in multipliers()]

>>> [6, 6, 6, 6]

Question 5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def extendList(val, list=[]):
list.append(val)
return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

# [10, 'a']
# [123]
# [10, 'a']

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

Note: The default empty list [] only created when the function defines.
So, list1 and list3 actually the same list.