Python B02 · Lesson 4 of 5

Loops

for loop · while loop · else with loops · break · continue · pass

Looping statements repeat a block of code multiple times. They are one of the most powerful tools in programming — without loops, you'd have to write the same code 100 times to do 100 things.

1. The for Loop

Used to iterate over a sequence — going through items one by one. Most commonly used when you know how many times to repeat.

for variable in sequence:
    code block

From your file (control-flow.py):

# Iterating over a string — one character at a time
for char in "Hello":
    print(char)
# Output: H e l l o (each on its own line)

Using range()

range() generates a sequence of numbers. It has three forms:

FormMeaningExampleGenerates
range(n)0 up to n-1range(5)0, 1, 2, 3, 4
range(start, stop)start up to stop-1range(2, 6)2, 3, 4, 5
range(start, stop, step)start to stop-1, by steprange(10, 0, -1)10, 9, 8 … 1
# Count down from 10 to 1 (from   file)
for num in range(10, 0, -1):
    print(num)

Nested for loops

A loop inside a loop. From the star pattern example:

# Print a 5×5 star grid
for _ in range(5):         # outer: 5 rows
    for _ in range(5):     # inner: 5 stars per row
        print("*", end=" ")
    print()                 # newline after each row
What is _ ?
The underscore _ is used as a variable when you don't actually need the loop variable. It's a convention that says "I'm not using this value."

2. The while Loop

Repeats a block of code as long as a condition stays True. Use when you don't know in advance how many iterations you need.

initialization
while condition:
    code block
    updation    # important! avoid infinite loop
Always update!
If you forget the updation step inside the while loop, the condition never becomes False and the loop runs forever (infinite loop). Always make sure the condition will eventually be False.

From file:

# Print from 11 down, by 2 (odd numbers descending)
num = 11
while num > 0:
    print(num)
    num -= 2    # updation — num decreases each time

Reverse a number (from file)

number = 1234
reverse = 0

while number > 0:
    remainder = number % 10        # get last digit
    reverse = reverse * 10 + remainder
    number = number // 10          # remove last digit

print(reverse)  # 4321

# How it works step by step:
# number=1234 → remainder=4, reverse=4,   number=123
# number=123  → remainder=3, reverse=43,  number=12
# number=12   → remainder=2, reverse=432, number=1
# number=1    → remainder=1, reverse=4321, number=0 → stop

3. else with Loops

Python allows an else after a loop. The else block runs only if the loop finishes normally (not interrupted by break).

for i in range(3):
    print(i)
else:
    print("Loop finished normally")
# Output: 0 1 2 Loop finished normally

4. Jumping Statements

Used to change the normal flow of a loop. Your teacher covers three: break, continue, and pass.

break — Exit the loop immediately

for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("completed the loop")
# Output: 0 1 2
# else does NOT run — loop was broken

continue — Skip this iteration, keep going

for i in range(5):
    if i == 3:
        continue       # skip i=3
    print(i)
else:
    print("completed the loop")
# Output: 0 1 2 4 (3 is skipped)
# else DOES run — loop completed normally

pass — Placeholder, do nothing

for i in range(5):
    if i == 3:
        pass           # does nothing — loop continues normally
    print(i)
else:
    print("completed the loop")
# Output: 0 1 2 3 4 completed the loop
# All numbers print including 3 — pass didn't skip anything
StatementEffectelse runs?
breakExits loop immediatelyNo
continueSkips current iteration onlyYes (loop finishes)
passDoes nothing — placeholderYes

🛠 Drills — Practice Time

Drill 1 Multiplication Table
Ask the user for a number. Print its multiplication table from 1 to 10 using a for loop.
Format: 5 x 1 = 5
n = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{n} x {i} = {n * i}")
Drill 2 Sum with while
Use a while loop to calculate the sum of numbers from 1 to 100.
i = 1
total = 0
while i <= 100:
    total += i
    i += 1
print("Sum:", total)   # 5050
Drill 3 Star Triangle
Print this triangle pattern using nested loops:
*
* *
* * *
* * * *
* * * * *
Hint: Outer loop for rows (1 to 5), inner loop prints stars based on current row number.
for row in range(1, 6):
    for col in range(row):
        print("*", end=" ")
    print()
Drill 4 Skip Multiples of 3
Print numbers from 1 to 15. Use continue to skip all multiples of 3.
for i in range(1, 16):
    if i % 3 == 0:
        continue
    print(i)
# Output: 1 2 4 5 7 8 10 11 13 14
Drill 5 Reverse a Number
Implement your number reversal algorithm. Ask the user for a number, then reverse its digits using a while loop.
number = int(input("Enter a number: "))
reverse = 0

while number > 0:
    remainder = number % 10
    reverse = reverse * 10 + remainder
    number = number // 10

print("Reversed:", reverse)

📝 Quiz — 8 Questions

Score: 0 / 8
1 What does range(5) generate?
2 range(10, 0, -1) generates which sequence?
3 What does break do to the loop's else block?
4 for i in range(5): if i==3: continue \n print(i) — what prints?
5 for i in range(5): if i==3: pass \n print(i) — what prints?
6 What are the three parts needed for a safe while loop?
7 Why does your teacher use _ as the loop variable in for _ in range(5)?
8 When should you prefer while over for?
← Lesson 3: Conditionals Next: Lesson 5 — Functions →