Loops are a fundamental concept in Python, allowing us to execute a block of code multiple times without redundant repetition. Python provides two main loop constructs:
while
loopfor
loop
In this guide, we will explore these loops in detail, covering syntax, use cases, best practices, and common pitfalls. We will also include basic, intermediate, and advanced programs demonstrating key concepts like break
, continue
, and pass
without using functions, classes, or modules.
Understanding the while
Loop
Syntax of while
Loop
while condition:
# Code to execute
- The loop runs as long as the condition is
True
. - If the condition becomes
False
, execution moves outside the loop.
Basic Example: Counting from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1
Using break
in while
Loop
num = 1
while num <= 10:
if num == 6:
break # Stops the loop when num reaches 6
print(num)
num += 1
Using continue
in while
Loop
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue # Skips even numbers
print(num)
Using pass
in while
Loop
The pass
statement is a placeholder and does nothing.
num = 1
while num <= 5:
pass # Placeholder for future code
num += 1
Intermediate Example: Finding the Sum of Digits
number = int(input("Enter a number: "))
sum_of_digits = 0
while number > 0:
sum_of_digits += number % 10
number //= 10
print("Sum of digits:", sum_of_digits)
Understanding the for
Loop
Syntax of for
Loop
for variable in iterable:
# Code to execute
- The
for
loop iterates over an iterable (like a list, string, or range). - It assigns each value to the variable and executes the loop body.
Basic Example: Iterating Over a Range
for i in range(1, 6):
print(i)
Using break
in for
Loop
for num in range(1, 11):
if num == 6:
break # Stops the loop when num reaches 6
print(num)
Using continue
in for
Loop
for num in range(1, 11):
if num % 2 == 0:
continue # Skips even numbers
print(num)
Using pass
in for
Loop
for i in range(5):
pass # Placeholder
Intermediate Example: Printing a Multiplication Table
n = int(input("Enter a number: "))
for i in range(1, 11):
print(n, "x", i, "=", n * i)
Advanced Looping Concepts
Looping Through Strings
text = "Python"
for char in text:
print(char)
Looping Through Lists
numbers = [10, 20, 30, 40]
for num in numbers:
print(num)
Looping Through Nested Loops
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Advanced Example: Finding Prime Numbers in a Range
start = int(input("Enter start: "))
end = int(input("Enter end: "))
for num in range(start, end + 1):
if num < 2:
continue
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
print(num)
Do’s and Don’ts of Using Loops
✅ Do’s
✔ Use loops to automate repetitive tasks.
✔ Use break
to exit loops when needed.
✔ Use continue
to skip specific iterations.
✔ Ensure while
loops have an exit condition to prevent infinite loops.
✔ Use range()
for indexed loops.
✔ Use else
with loops for additional logic after iteration.
❌ Don’ts
✘ Avoid infinite loops without exit conditions.
✘ Don’t modify an iterable while looping through it.
✘ Avoid excessive nesting, as it reduces readability.
✘ Don’t use break
unnecessarily, unless required.
✘ Avoid using pass
unless it’s a placeholder.
Exceptions in Loops
- Infinite Loops
while True:
print("This will run forever!")
- 🔴 Solution: Always include an exit condition.
- Modifying an Iterable While Iterating
numbers = [1, 2, 3, 4]
for num in numbers:
numbers.remove(num) # Causes unexpected behavior
- 🔴 Solution: Iterate over a copy (
numbers[:]
) instead.
- Index Out of Range in
for
Loopslst = [10, 20, 30]
for i in range(len(lst) + 1):
print(lst[i]) # Causes IndexError
- 🔴 Solution: Ensure
range(len(lst))
is correctly defined.
Conclusion
Mastering loops in Python is essential for writing efficient code. The while
loop is useful when the number of iterations is unknown, while the for
loop is preferred when iterating over a sequence.
By following best practices and understanding pitfalls, you can avoid errors and optimize performance. Experiment with the example programs to solidify your knowledge of loop control flow.
Happy coding!