Python: Loops and Iteration in Python
Last updated: 2026-09-22
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"
1. 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 (⭐)
▶ Try it YourselfOutput:
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.
2. 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 (⭐)
▶ Try it YourselfOutput:
---
▶ Example: Iterating with Index (⭐⭐)
▶ Try it YourselfOutput:
Student 1: Alice
Student 2: Bob
Student 3: Charlie
Student 4: Diana
enumerate(). We'll cover it in a later lesson.
3. 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 (⭐)
▶ Try it YourselfOutput:
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 (⭐⭐)
▶ Try it YourselfOutput:
# Executed successfully
This shows the strength of while: we don't know in advance how many iterations are needed — we only know when to stop.
4. break and continue — Brake and Skip
(1) break — Exit the Loop Immediately
When a condition is met, break jumps out of the entire loop, disregarding any remaining iterations.
(2) 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 (⭐)
▶ Try it YourselfOutput:
=== break example ===
\n=== continue example ===
▶ Example: break in Practice — Search and Stop (⭐⭐)
▶ Try it YourselfOutput:
No even numbers in the list
▶ Example: continue in Practice — Process Only Valid Data (⭐⭐)
▶ Try it YourselfOutput:
# Executed successfully
5. 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 (⭐⭐)
▶ Try it YourselfOutput:
# Executed successfully
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...".
6. 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 (⭐⭐)
▶ Try it YourselfOutput:
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 (⭐⭐)
▶ Try it YourselfOutput:
(1,1)
(2,1) (2,2)
(3,1) (3,2) (3,3)
7. 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.
▶ Try it YourselfOutput:
🎯 Guess the Number! I
Please enter a valid number!
Too low, try higher!
Too high, try lower!
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.
▶ Try it YourselfSample run:
Enter your password: Hello123
Password strength: 3/5
Suggestions:
❌ Missing special character
Enter your password: P@ssw0rd!
Password strength: 5/5
🎉 Strong password!
8. 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.for i in range(len(list)) Pythonic?for item in list. Only use range(len(...)) when you specifically need indices — and even then, enumerate() is more elegant.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!