12 snippets: predict what each one prints. Score 11 or more and the Python foundations (Modules 1–3) are marked as skipped. No running the code, no pressure; it’s only here to save you time.
1. Random seeds: what does this print? import random
random.seed(1)
a = random.random()
random.seed(1)
b = random.random()
print(a == b) True False it varies from run to run an error: seed takes no number
2. Loops: what does this print? for i in range(3):
print(i, end=' ') 1 2 3 0 1 2 0 1 2 3 3
3. Functions: what does this print? def f(a, b=2):
return a * b
print(f(3)) 5 an error: b is missing 6 32
4. Lists: what does this print? names = ['ann', 'bob', 'cy']
print(names[-1], len(names)) ann 3 cy 2 cy 3 an error: -1 is not an index
5. Nested lists: what does this print? m = [[1, 2], [3, 4]]
print(m[1][0]) 2 3 [3, 4] 1
6. Dicts: what does this print? counts = {}
for ch in 'banana':
counts[ch] = counts.get(ch, 0) + 1
print(counts['a']) 1 3 6 0
7. Sets and sorting: what does this print? print(sorted(set('hello'))) ['h', 'e', 'l', 'l', 'o'] ['e', 'h', 'l', 'o'] ['h', 'e', 'l', 'o'] 'ehlo'
8. List comprehensions: what does this print? print([n * n for n in range(5) if n % 2 == 0]) [0, 4, 16] [4, 16] [1, 9] [0, 1, 4, 9, 16]
9. Classes: what does this print? class Box:
def __init__(self, v):
self.v = v
def double(self):
return Box(self.v * 2)
print(Box(5).double().v) 5 10 Box(10) an error
10. Recursion: building a list: what does this print? def countdown(n):
if n == 0:
return []
return [n] + countdown(n - 1)
print(countdown(3)) [3, 2, 1, 0] [1, 2, 3] [3, 2, 1] it never stops
11. Recursion: print after the call: what does this print? def show(n):
if n == 0:
return
show(n - 1)
print(n, end=' ')
show(3) 3 2 1 1 2 3 0 1 2 3 it never stops
12. zip: what does this print? pairs = list(zip('abc', 'bcd'))
print(pairs[1]) ('a', 'b') ('b', 'c') ('c', 'd') 'bc'
Answer all 12 to see your result