Lesson 5 of 14 · 8 min

Loops

A for loop repeats code for each item in a sequence. range makes sequences of numbers:

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

range can take a start, a stop and a step. The stop number itself is not included:

Code Gives
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

The indented lines are the body of the loop. The first line that is not indented runs after the loop has finished.

while

A while loop repeats as long as a condition is true:

savings = 0
weeks = 0
while savings < 100:
    savings += 15        # same as savings = savings + 15
    weeks += 1
print(f"{weeks} weeks")  # 7 weeks

If the condition never becomes false the loop runs forever. Here, programs running more than 10 seconds are stopped for you.

Your task

Print a rocket countdown: the numbers 10 down to 1, one per line, then Liftoff!.

main.py
# Count down from 10 to 1, then print Liftoff!

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…