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 6range(stop)stops beforestop.range(start, stop, step)also works, including negative steps.enumerategives you the position without index arithmetic.zipstops at the shortest input.breakleaves the loop.continueskips 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) # 1Your 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.
The explanation opens here once every check passes.