Lesson 7 of 15

Loops

Loops

Python has for and while loops. for iterates over any iterable.

for Loop

for i in range(5):         # 0, 1, 2, 3, 4
    print(i)

for item in ["a", "b"]:   # iterate a list
    print(item)

for i, v in enumerate(["a", "b"]):  # index + value
    print(i, v)

range()

range(5)        # 0, 1, 2, 3, 4
range(1, 6)     # 1, 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8
range(5, 0, -1) # 5, 4, 3, 2, 1

while Loop

n = 10
while n > 0:
    print(n)
    n //= 2

break and continue

for i in range(10):
    if i == 5:
        break      # exit loop
    if i % 2 == 0:
        continue   # skip to next iteration
    print(i)

Your Task

Implement collatz(n) that:

  • Returns the length of the Collatz sequence starting from n
  • The sequence: if n is even, next = n // 2; if odd, next = 3 * n + 1; stop when n == 1
  • Count n itself as the first step

Example: collatz(6) → 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 → length 9

Pyodide loading...
Loading...
Click "Run" to execute your code.