Python 3 — Repeating Actions with Loops

🐍 Python 3 🟢 Lesson 6 📅 July 2026

Loops allow you to run the same block of code multiple times. Instead of copy-pasting the same instruction ten times, you can tell the computer to repeat it using a loop. Python offers two main types of loops: 'while' loops and 'for' loops.

1 While Loops

A while loop runs as long as a specified condition remains True. Be careful to change the variable inside the loop, or it will run forever (creating an infinite loop):

Python 3 — While Loop ▶ Run Code
countdown = 5

while countdown > 0:
    print(f"Countdown: {countdown}")
    countdown = countdown - 1  # Decrement variable

print("Blast off! 🚀")
2 For Loops & The range() Function

A for loop iterates over a sequence. In Python, you frequently pair it with the range() function to run code a specific number of times. Note that range(start, stop) goes up to but does not include the 'stop' value:

Python 3 — For Loop & Range ▶ Run Code
# Loop from 0 to 4 (runs 5 times)
for i in range(5):
    print(f"Count: {i}")

print("-" * 20)

# Loop from 1 to 5
for num in range(1, 6):
    print(f"Number: {num}")
3 Loop Controls: break & continue

Sometimes you need to alter the loop's natural flow:

  • break: Instantly terminates the loop, jumping to code below it.
  • continue: Skips the rest of the current iteration and jumps back to the top to start the next iteration.
Python 3 — Loop Controls ▶ Run Code
# Break example
for n in range(1, 10):
    if n == 5:
        break # Exit loop
    print(n) # Prints 1, 2, 3, 4

print("-" * 20)

# Continue example
for val in range(1, 6):
    if val == 3:
        continue # Skip 3
    print(val) # Prints 1, 2, 4, 5
⚠️ Infinite Loop Recovery:

If you accidentally write a program with an infinite loop (e.g. while True: print("Help!")), the compiler output panel will lag or timeout. In Our Compiler, you can simply click the **Stop** button to kill the Docker container instantly!

4 Coding Challenge

Write a program that prints only the **even** numbers between 1 and 20. Use a 'for' loop and an 'if' statement to check if the remainder of the number divided by 2 is 0 (using the modulo % operator).