PythiloLesson 10 of 30 · progress kept in this browser

Loops

for walks over anything iterable. while repeats as long as a condition holds.

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

names = ["a", "b"]
for i, n in enumerate(names):
    print(i, n)     # 0 a, then 1 b

for x, y in zip([1, 2], [3, 4]):
    print(x + y)    # 4, then 6
  • range(stop) stops before stop. range(start, stop, step) also works, including negative steps.
  • enumerate gives you the position without index arithmetic.
  • zip stops at the shortest input.
  • break leaves the loop. continue skips to the next pass.

Prefer for when you know what you are walking over. Use while when you only know when to stop:

n = 40
while n > 1:
    n = n // 2
print(n)  # 1
Your task

Write collatz_steps(n): repeatedly halve even numbers and turn odd n into 3 * n + 1, returning how many steps it takes to reach 1. Write first_negative_index(numbers) returning the index of the first negative number, or -1 if there is none.