the full guide

Loops: for, while and range

Repeat work without repeating code. This is where programs start to feel powerful.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

for: do this for each item

for_loop.py
fruits = ["apple", "mango", "banana"]

for fruit in fruits:
    print("I like", fruit)

for letter in "AI":
    print(letter)

Output

I like apple
I like mango
I like banana
A
I

range: counting

range_loop.py
for i in range(3):          # 0, 1, 2 (stops before 3)
    print(i)

for i in range(2, 11, 4):   # Start 2, stop before 11, jump by 4
    print(i)

total = 0
for i in range(1, 101):     # Add 1 to 100
    total += i
print("Sum of 1 to 100:", total)

Output

0
1
2
2
6
10
Sum of 1 to 100: 5050

while: repeat until something changes

while_loop.py
money = 100
days = 0

while money > 0:
    money -= 30
    days += 1

print("Money ran out after", days, "days")

Output

Money ran out after 4 days

break and continue

break_continue.py
for number in range(1, 10):
    if number == 3:
        continue      # Skip this one
    if number == 6:
        break         # Stop the whole loop
    print(number)

Output

1
2
4
5

Code challenge

Print the 7 times table up to 7 × 10.

for i in range(1, 11): print(f"7 x {i} = {7 * i}")

Finished reading?