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:


Related Keywords / Statements:enumerate() continue print() range() while break False else True for

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:

TEXT 📖 Display only
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 Yourself

Output:

TEXT 📖 Display only
I like apple
I like banana
I like orange
I like grape
---
P
y
t
h
o
n
💡 Naming tip: Name the loop variable in singular form. If the list is 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 Yourself

Output:

TEXT 📖 Display only
---

▶ Example: Iterating with Index (⭐⭐)

▶ Try it Yourself

Output:

TEXT 📖 Display only
Student 1: Alice
Student 2: Bob
Student 3: Charlie
Student 4: Diana
💡 More elegant way: In Python, if you need both index and element, use 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:

TEXT 📖 Display only
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 Yourself

Output:

TEXT 📖 Display only
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Launch!
⚠️ Infinite loop warning: If you forget 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 Yourself

Output:

TEXT 📖 Display only
# 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 Yourself

Output:

TEXT 📖 Display only
=== break example ===
\n=== continue example ===

▶ Example: break in Practice — Search and Stop (⭐⭐)

▶ Try it Yourself

Output:

TEXT 📖 Display only
No even numbers in the list

▶ Example: continue in Practice — Process Only Valid Data (⭐⭐)

▶ Try it Yourself

Output:

TEXT 📖 Display only
# 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 Yourself

Output:

TEXT 📖 Display only
# Executed successfully

In this example:

💡 Many beginners find 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 Yourself

Output:

TEXT 📖 Display only
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
⚠️ Performance tip: Total executions = outer count × inner count. N-level nesting means exponential growth. Be careful with 3+ levels of nesting when dealing with large datasets.

▶ Example: break Only Affects the Current Level (⭐⭐)

▶ Try it Yourself

Output:

TEXT 📖 Display only
(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 Yourself

Output:

TEXT 📖 Display only
🎯 Guess the Number! I
Please enter a valid number!
Too low, try higher!
Too high, try lower!

Key points:

▶ Example 2: Password Strength Checker (⭐⭐⭐)

Check the user's password and score its strength.

▶ Try it Yourself

Sample run:

TEXT 📖 Display only
Enter your password: Hello123
Password strength: 3/5
Suggestions:
  ❌ Missing special character
TEXT 📖 Display only
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

Related Keywords / Statements:enumerate() continue print() range() while break False else True for

❓ FAQ

Q When should I use for vs while?
A Use 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


📝 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:

  1. Use while True and break
  2. Handle division by zero
  3. Handle invalid operators (show a hint, don't exit)
  4. Use continue to re-prompt on invalid input

Sample run:

TEXT 📖 Display only
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!
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏