Skip to content

Run it in your head

Read · 1 of 3

Be the computer

Before running code, run it in your head. Write down each variable and update it line by line, like a small table.

It feels slow at first, but it's the fastest way to find out what code *really* does, as opposed to what its names suggest.

Read this lesson as text

Track the variables on paper and predict the output.

Be the computer

Before running code, run it in your head. Write down each variable and update it line by line, like a small table.

It feels slow at first, but it's the fastest way to find out what code *really* does, as opposed to what its names suggest.

Skipping some

total = 0
for i in range(1, 5):
    if i % 2 == 0:
        continue
    total += i * i
print(total)

What does this print?

  • 30
  • 10
  • 20
Show the answer

10 range(1, 5) is 1, 2, 3, 4. continue skips the even ones, so only 1×1 + 3×3 = 10 is added.

Counting steps

n = 37
steps = 0
while n != 1:
    n = n // 2 if n % 2 == 0 else n - 1
    steps += 1
print(steps)

What does this print?

  • 6
  • 5
  • 7
Show the answer

7 37 → 36 → 18 → 9 → 8 → 4 → 2 → 1: seven steps. Halve when even, subtract 1 when odd.