Loops
When writing code, you often encounter scenarios where you need to repeat the same action — printing numbers 1 to 100, processing every element in a list, or continuously asking for user input until you get a valid answer.
Writing 100 lines of print() for 100 numbers is impractical. That's where loops come in. Python provides two types of loops:
forloop — for "iterating" over a sequence (list, string, range, etc.)whileloop — for "execute while condition is true"
for Loop Basics
The for loop is the most commonly used loop in Python. Its core idea: take elements from a sequence one by one, executing the same code block each time.
Basic syntax:
for variable in sequence:
code to repeat
The variable is assigned each element in the sequence, and the indented block is executed for each one.
Example: Iterating Over Lists and Strings (⭐)
# Iterate over a list
fruits = ["apple", "banana", "orange", "grape"]
for fruit in fruits:
print(f"I like {fruit}")
print("---")
# Iterate over a string — characters one by one
for char in "Python":
print(char)
Output:
I like apple
I like banana
I like orange
I like grape
---
P
y
t
h
o
n
fruits, use fruit; if students, use student. The code reads like natural language.
The range() Function — Generate Number Sequences
When you need to repeat a fixed number of times, range() is your best friend.
range() has three forms:
| Syntax | Meaning | Example | Result |
|---|---|---|---|
range(stop) |
0 → stop-1 | range(5) |
0,1,2,3,4 |
range(start, stop) |
start → stop-1 | range(2, 6) |
2,3,4,5 |
range(start, stop, step) |
With step | range(1, 10, 2) |
1,3,5,7,9 |
Note:
range()does not include the stop value — same as slicing, it's "up to but not including."
Example: Controlling Loop Count with range (⭐)
# Print 1 to 5
for i in range(1, 6):
print(f"Loop {i}")
print("---")
# Step of 2: print even numbers from 0 to 10
for i in range(0, 11, 2):
print(i, end=" ") # end=" " prevents newlines
# Output: 0 2 4 6 8 10
Example: Iterating with Index (⭐⭐)
students = ["Alice", "Bob", "Charlie", "Diana"]
# Get both index and element
for i in range(len(students)):
print(f"Student {i + 1}: {students[i]}")
Output:
Student 1: Alice
Student 2: Bob
Student 3: Charlie
Student 4: Diana
enumerate(). We'll cover it in a later lesson.
while Loop
The difference between while and for: for knows how many times to loop; while only knows when to stop.
Basic syntax:
while condition:
code to repeat
Before each iteration, the condition is checked. If it's True, the code block runs, then the condition is checked again... until it becomes False.
Example: Countdown (⭐)
count = 5
while count > 0:
print(f"Countdown: {count}")
count -= 1 # Decrement by 1 each time — very important!
print("Launch!")
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Launch!
count -= 1, the condition count > 0 is always True, and the program runs forever until you force-stop it. When writing while loops, always ensure the condition can become False at some point.
Example: Typical while Usage — Until a Specific Value (⭐⭐)
# Keep halving until less than 1
num = 100
while num >= 1:
print(num, end=" → ")
num /= 2
# Output: 100 → 50.0 → 25.0 → 12.5 → 6.25 → 3.125 → 1.5625 → 0.78125
This shows the strength of while: we don't know in advance how many iterations are needed — we only know when to stop.
break and continue — Brake and Skip
break — Exit the Loop Immediately
When a condition is met, break jumps out of the entire loop, disregarding any remaining iterations.
continue — Skip the Current Iteration
When a condition is met, continue skips the rest of the current iteration and moves to the next one.
Example: break vs continue (⭐)
print("=== break example ===")
for i in range(1, 10):
if i == 5:
break # End the loop when reaching 5
print(i, end=" ")
# Output: 1 2 3 4
print("\n=== continue example ===")
for i in range(1, 10):
if i == 5:
continue # Skip 5, continue with the rest
print(i, end=" ")
# Output: 1 2 3 4 6 7 8 9
Example: break in Practice — Search and Stop (⭐⭐)
# Search for the first even number in a list
numbers = [3, 7, 9, 2, 5, 8, 1]
for num in numbers:
if num % 2 == 0:
print(f"Found first even number: {num}")
break # Stop searching once found
else:
print("No even numbers in the list") # This else belongs to the for loop
Example: continue in Practice — Process Only Valid Data (⭐⭐)
# Process only positive numbers, skip negatives and zero
data = [3, -5, 0, 8, -2, 7, 0, 4]
positive_sum = 0
for num in data:
if num <= 0:
continue # Skip invalid data
positive_sum += num
print(f"Sum of positive numbers: {positive_sum}") # Output: 22 (3+8+7+4)
for-else and while-else — "Normal Completion Bonus"
This is a unique Python syntax feature, not found in many other languages.
The else block executes when the loop completes normally (without being interrupted by break). Think of it as: "if the loop wasn't interrupted, run this bonus code."
Example: Prime Number Check (⭐⭐)
num = 17
for i in range(2, num):
if num % i == 0:
print(f"{num} is not prime, divisible by {i}")
break
else:
print(f"{num} is prime!") # Executes only if no break occurred
In this example:
- If a divisor is found,
breakis triggered,elsedoesn't run - If no divisor is found after checking all possibilities, the loop ends normally, and
elseruns
for-else counterintuitive. Remember it as: else means "if no break happened, then...".
Nested Loops
A loop inside another loop is a nested loop. For each iteration of the outer loop, the inner loop runs a full round.
Example: Multiplication Table (⭐⭐)
for i in range(1, 10): # Outer loop: rows
for j in range(1, i + 1): # Inner loop: columns
print(f"{j}×{i}={i*j}", end="\t")
print() # Newline after each row
Output:
1×1=1
1×2=2 2×2=4
1×3=3 2×3=6 3×3=9
1×4=4 2×4=8 3×4=12 4×4=16
1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81
Example: break Only Affects the Current Level (⭐⭐)
for i in range(1, 4):
for j in range(1, 10):
if j > i:
break # Only breaks the inner loop
print(f"({i},{j})", end=" ")
print()
Output:
(1,1)
(2,1) (2,2)
(3,1) (3,2) (3,3)
Comprehensive Examples
Example 1: Guess the Number Game (⭐⭐)
The system generates a random number between 1 and 100. The player guesses, and the system gives hints ("too high" or "too low") until the player guesses correctly.
import random
# Generate a random target
target = random.randint(1, 100)
attempts = 0
print("🎯 Guess the Number! I'm thinking of a number between 1 and 100.")
while True: # Infinite loop, exit via break
try:
guess = int(input("Enter your guess: "))
except ValueError:
print("Please enter a valid number!")
continue
attempts += 1
if guess < target:
print("Too low, try higher!")
elif guess > target:
print("Too high, try lower!")
else:
print(f"🎉 Congratulations! It's {target}!")
print(f"You guessed it in {attempts} attempts.")
break # Exit the loop on correct guess
Key points:
while Truewithbreakis a very common pattern in Pythontry-exceptcatches non-numeric input,continueprompts the user againbreakexits the loop when guessed correctly
Example 2: Password Strength Checker (⭐⭐⭐)
Check the user's password and score its strength.
password = input("Enter your password: ")
score = 0
feedback = []
# 1. Check length
if len(password) >= 8:
score += 1
else:
feedback.append("❌ Password is less than 8 characters")
# 2. Check character types
has_upper = False
has_lower = False
has_digit = False
has_special = False
special_chars = "!@#$%^&*"
for char in password:
if char.isupper():
has_upper = True
elif char.islower():
has_lower = True
elif char.isdigit():
has_digit = True
elif char in special_chars:
has_special = True
# Score based on checks
checks = [has_upper, has_lower, has_digit, has_special]
score += sum(checks)
if not has_upper:
feedback.append("❌ Missing uppercase letter")
if not has_lower:
feedback.append("❌ Missing lowercase letter")
if not has_digit:
feedback.append("❌ Missing digit")
if not has_special:
feedback.append("❌ Missing special character")
# 3. Output results
print(f"\nPassword strength: {score}/5")
if feedback:
print("Suggestions:")
for item in feedback:
print(f" {item}")
else:
print("🎉 Strong password!")
Sample run:
Enter your password: Hello123
Password strength: 3/5
Suggestions:
❌ Missing special character
Enter your password: P@ssw0rd!
Password strength: 5/5
🎉 Strong password!
Common Use Cases
| Scenario | Recommended Loop | Notes |
|---|---|---|
| Iterating over list/tuple/set | for |
Process elements one by one |
| Iterating over dictionary key-value pairs | for |
Use .items() |
| Repeat N times | for + range() |
Fixed number of iterations |
| Until condition is met | while |
Unknown number of iterations |
| Read file until EOF | for / while |
File objects are iterable |
| User input validation | while + break |
Loop until valid input |
| Infinite loop (server, game loop) | while True |
Exit via break |
❓ FAQ
for vs while?for when you know the number of iterations (iterating over lists/ranges/strings). Use while when you know the stopping condition (waiting for input, approaching a value). They're often interchangeable, but choosing the right one makes code clearer.
⚠️ Q: Is for i in range(len(list)) Pythonic? A: Not really. Python prefers direct iteration: for item in list. Only use range(len(...)) when you specifically need indices — and even then, enumerate() is more elegant.
Q: What if I have too many nested loops? A: Nesting beyond 3 levels hurts readability. Solutions: extract inner loops into functions, use itertools for combinations, or rethink the algorithm.📖 Summary
forloop iterates over sequences (lists, strings, range, etc.)range(start, stop, step)generates number sequences; stop is exclusive; step can be negativewhileloop is condition-driven; avoid infinite loopsbreakexits the entire loop;continueskips the current iterationfor-else/while-else— Python-specific;elseruns when the loop wasn't exited viabreak- Nested loops: each outer iteration triggers a full inner loop; total = product of counts
📝 Exercises
⭐ Exercise 1: Sum of Even Numbers
Use a for loop and range() to calculate the sum of all even numbers between 1 and 100.
Hint: range(2, 101, 2) gets you there in one step.
⭐⭐ Exercise 2: Fibonacci Sequence
Definition: the first two numbers are 1, and each subsequent number is the sum of the previous two. Sequence: 1, 1, 2, 3, 5, 8, 13, 21, ...
Use a while loop to output all Fibonacci numbers not exceeding 1000.
Hint: use three variables a, b for the current two numbers, compute a + b for the next, then shift.
⭐⭐⭐ Exercise 3: Simple Calculator
Write a program that repeatedly asks for two numbers and an operator (+, -, *, /), outputs the result.
Enter q to quit.
Requirements:
- Use
while Trueandbreak - Handle division by zero
- Handle invalid operators (show a hint, don't exit)
- Use
continueto re-prompt on invalid input
Sample run:
Enter first number: 10
Enter operator (+ - * /): /
Enter second number: 3
= 3.333...
Enter first number: 8
Enter operator (+ - * /): %
Invalid operator, please use + - * /
Enter first number: 8
Enter operator (+ - * /): /
Enter second number: 0
Error: cannot divide by zero
Enter first number: q
Goodbye!



