Python Loops – The Complete Guide to for, while, and Control Statements
Introduction – Why Loops Matter in Python
In the world of programming, repetitive tasks are everywhere. Whether it’s processing items in a list, checking user input until it’s valid, or executing code until a condition is met—loops provide an efficient way to handle them.
In Python, loops aren’t just basic iteration tools—they’re flexible, powerful, and easy to understand. With constructs like for, while, for-else, and control flow modifiers (break, continue, pass), Python gives developers precise control over code execution flow.
In this guide, you’ll master:
- How
forandwhileloops work in Python - When to use
for-elseand nested loops - How
break,continue, andpassaffect loop behavior - Real-world examples and line-by-line breakdowns
for Loop in Python
Syntax:
for item in iterable:
# code block
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Explanation:
- The loop iterates over each item in the list
fruits. fruittakes the value of each list element one at a time.print(fruit)executes for every item.
Tip: Use for loops with lists, tuples, dictionaries, strings, and ranges.
while Loop in Python
Syntax:
while condition:
# code block
Example:
count = 1
while count <= 5:
print(count)
count += 1
Explanation:
- Executes as long as
count <= 5. - Increments
countafter each iteration. - Exits when
countbecomes 6.
Warning: Always ensure your while condition will eventually become False, or you’ll end up in an infinite loop.
for-else Loop
Python’s for loop can include an else block, which executes only if the loop wasn’t terminated by a break.
Example:
nums = [1, 3, 5, 7]
for num in nums:
if num % 2 == 0:
print("Even number found:", num)
break
else:
print("No even number found.")
Explanation:
- The loop checks for even numbers.
- If
breakisn’t triggered, theelseblock runs. - Great for searching scenarios.
Nested Loops
A loop inside another loop is called a nested loop. Useful in multi-dimensional data structures like matrices or grids.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} * {j} = {i * j}")
Explanation:
- Outer loop iterates through
i = 1 to 3. - Inner loop iterates through
j = 1 to 3. - Produces a multiplication table from 1×1 to 3×3.
Warning: Nested loops increase time complexity. Use only when necessary.
Loop Control Statements
break – Exit the Loop Early
for num in range(1, 10):
if num == 5:
break
print(num)
Output: 1 2 3 4
Stops loop when num equals 5.
continue – Skip the Current Iteration
for num in range(1, 6):
if num == 3:
continue
print(num)
Output: 1 2 4 5
⏭️ Skips printing 3.
pass – Do Nothing (Placeholder)
for char in "abc":
pass
Used when syntax requires a statement but logic isn’t ready yet.
Real-World Example – FizzBuzz Using Loops
for i in range(1, 16):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Combines for, if-elif, and modulus logic to print:
- “Fizz” for multiples of 3
- “Buzz” for multiples of 5
- “FizzBuzz” for multiples of both
Summary – Key Takeaways
-
forloops are great for iterating over known sequences. -
whileloops are ideal when the number of iterations is unknown. -
for-elseruns theelseonly ifbreakdoesn’t occur. - Nested loops allow multi-dimensional iteration but can be slow.
- 🚦 Use
break,continue, andpassto control loop behavior.
FAQ Section
What is the difference between break and continue in Python loops?
break exits the loop entirely, while continue skips the current iteration and proceeds to the next one.
When should I use a for loop instead of a while loop?
Use for when iterating over a known sequence (e.g., list or range). Use while when repeating based on a condition.
How does for-else work in Python?
The else block executes only if the loop completes without a break.
Can I have else in a while loop too?
Yes, Python allows else with while loops in the same way it does with for loops.
What is the best way to avoid infinite while loops?
Ensure the loop’s condition will eventually be False, and test with small ranges first.
Share Now :
