Skip to main content

Already know Python?

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)
2. Loops: what does this print?
for i in range(3):
    print(i, end=' ')
3. Functions: what does this print?
def f(a, b=2):
    return a * b

print(f(3))
4. Lists: what does this print?
names = ['ann', 'bob', 'cy']
print(names[-1], len(names))
5. Nested lists: what does this print?
m = [[1, 2], [3, 4]]
print(m[1][0])
6. Dicts: what does this print?
counts = {}
for ch in 'banana':
    counts[ch] = counts.get(ch, 0) + 1
print(counts['a'])
7. Sets and sorting: what does this print?
print(sorted(set('hello')))
8. List comprehensions: what does this print?
print([n * n for n in range(5) if n % 2 == 0])
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)
10. Recursion: building a list: what does this print?
def countdown(n):
    if n == 0:
        return []
    return [n] + countdown(n - 1)

print(countdown(3))
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)
12. zip: what does this print?
pairs = list(zip('abc', 'bcd'))
print(pairs[1])