Type the expressions below in python interactively, and try to explain what's happening in each case: a. 2 ** 16 2 / 5, 2 / 5.0 b. "spam" + "eggs" S = "ham" "eggs " + S S * 5 S[:0] "green %s and %s" % ("eggs", S) c. ('x',) [0] ('x', 'y') [1] d. L = [1,2,3] + [4,5,6] L, L[:], L[:0], L[-2], L[-2:] ([1,2,3] + [4,5,6]) [2:4] [L[2], L[3]] L.reverse(); L L.sort(); L L.index(4)
a.
a=2**16 #2 is raised to the power of 16, the output will be 65536
b=2 / 5 #2 is divided by an integer,5, output:0.4
c=2 / 5.0 #2 is divided by a float,5.0, output: 0.4
b.
a="spam" + "eggs" #adds the two strings, spam and eggs. Output: spameggs
S = "ham" #initialize S to 'ham'
cb="eggs " + S #add 'eggs ' to the value of S. Output: egg ham
S * 5 #multiply the value of S by 5. Output: hamhamhamhamham
c=S[:0] #return the elements of S upto index 0
"green %s and %s" % ("eggs", S) #prints green eggs and ham
c.
('x',) [0] #output the first element, x
('x', 'y') [1] #output the second element, y
d.
L = [1,2,3] + [4,5,6] #combine the two lists. Output [1,2,3,4,5,6]
L #prints the whole list
L[:] #prints the whole list
L[:0] #prints an empty list
L[-2] #prints the second last element in the list
L[-2:] #prints the last two elements in the list
([1,2,3] + [4,5,6]) [2:4] #add the two lists and prints the elements from index 2 to 4
[L[2], L[3]] #prints a list consisting of element at 2 and 3 indixes. Output [3,4]
L.reverse(); L #reverse the list
L.sort(); L #sort the list
L.index(4) #returns the index of element 4 in the list
Comments
Leave a comment