Loop Statements: Repeat Tasks Efficiently
Introduction
In this chapter, you will learn loop statements in Python, mainly for and while. Loops help you run repeated actions without writing the same code again and again. This is a core skill for processing lists, validating input, and automating everyday coding tasks.
Prerequisites
- Python
3.10+installed - Basic understanding of variables, operators, and strings
- Ability to run
.pyfiles in terminal or IDE
What Is a Loop
A loop repeats a block of code multiple times.
Think of it like:
- A workout routine: repeat one set many times.
- A to-do batch: apply the same action to each item.
Without loops, repeated logic becomes long and hard to maintain.
1) The for Loop
Use for when you want to iterate over a known sequence (like a list, string, or range).
# Print numbers from 1 to 5
for number in range(1, 6):
print(number)range(1, 6) means: start at 1, stop before 6.
Looping through a list:
# Store a list of fruits
fruits = ["apple", "banana", "orange"]
# Print each fruit
for fruit in fruits:
print(fruit)2) The while Loop
Use while when repetition depends on a condition.
# Start counter
count = 1
# Repeat while condition is true
while count <= 5:
print(count)
count += 1This loop continues until count <= 5 becomes false.
Warning
Always make sure while loops can eventually stop.
If the condition never becomes false, you create an infinite loop.
3) Control Keywords in Loops
Three helpful loop controls:
break: stop loop immediatelycontinue: skip current iteration, go to nextpass: placeholder, do nothing
break Example
# Search for a target number
for number in range(1, 10):
if number == 6:
print("Found 6, stop now.")
break
print(number)continue Example
# Skip even numbers
for number in range(1, 8):
if number % 2 == 0:
continue
print(number)pass Example
# Placeholder loop structure
for _ in range(3):
pass
print("Loop completed.")4) Nested Loops
A nested loop is a loop inside another loop.
# Print a small coordinate grid
for row in range(1, 4):
for col in range(1, 4):
print(f"({row}, {col})", end=" ")
print()Nested loops are useful for tables, matrix-like data, and pattern printing.
5) Real Mini Example: Password Retry
This example simulates a login retry process.
# Store the correct password
correct_password = "python123"
# Set max attempts
max_attempts = 3
# Track current attempt count
attempt = 0
# Repeat until attempts are used up
while attempt < max_attempts:
# Ask user for password
entered = input("Enter password: ")
# Check password
if entered == correct_password:
print("Login successful.")
break
# Increase attempt count
attempt += 1
print(f"Wrong password. Remaining attempts: {max_attempts - attempt}")
else:
# Execute when loop ends without break
print("Account locked. Please try again later.")This pattern appears in real authentication and validation flows.
Tip
Best Practice
Prefer for when iteration count is predictable.
Use while when stopping logic depends on runtime conditions.
Surprise Practice Challenge
Build a tiny "Guess the Number" game:
- Set a secret number (for example,
7) - Let user guess repeatedly
- Print hints:
Too highorToo low - Stop when guessed correctly
- Print how many attempts were used
Reference implementation:
# Set secret number
secret = 7
# Track attempts
attempts = 0
# Keep asking until correct
while True:
# Read user guess as integer
guess = int(input("Guess the number (1-10): "))
attempts += 1
# Compare and provide hint
if guess < secret:
print("Too low.")
elif guess > secret:
print("Too high.")
else:
print(f"Correct! You used {attempts} attempts.")
breakThis feels like a game, but it teaches real control-flow thinking.
Common Beginner Mistakes
Mistake 1: Off-by-One Errors
range(1, 6) includes 1 to 5, not 6.
Mistake 2: Infinite while Loops
Forgetting to update loop variables makes conditions stay true forever.
Mistake 3: Wrong Indentation
Python uses indentation to define loop blocks. Misalignment changes behavior or causes errors.
FAQ
When should I choose for over while?
Use for when you iterate through a sequence or fixed count. Use while when the end condition is uncertain.
Can I use break in both for and while?
Yes. break works in both loop types and exits the nearest loop immediately.
What is the purpose of else after a loop?
Loop else runs only if the loop finishes normally (without hitting break).
Are nested loops bad practice?
Not always. They are useful for 2D data and combinations, but be careful with performance in large datasets.