Have you ever needed to perform an action repeatedly, like counting numbers or displaying a message multiple times? Instead of duplicating code, loops offer a more efficient and elegant way to automate repetition in Python.
Python provides two main types of loops: for loops and while loops. Let’s explore how they work and how you can use them effectively!
What are loops?
Loops allow you to write a block of code once and execute it multiple times. They are invaluable for automating repetitive tasks, saving time and effort. Let’s dive into the two main types of loops in Python.
for
loops: Iterating over a sequence
A for
Syntax
for item in sequence:
# Do something with item
Example: Iterating over a list
for number in [1, 2, 3, 4, 5]:
print("This is number:", number)
Explanation:
The loop iterates over the list [1, 2, 3, 4, 5]
. During each iteration, the variable number
takes one value from the list, which is then printed.
Using range()
with for
loops
range()
If you need a sequence of numbers but don’t have a predefined list, use the range()
Example:
for i in range(5):
print("Hello!")
Explanation:
generates numbers from 0 to 4. The loop runs five times, printing "Hello!"
on each iteration.
while
loops: Repeating based on a condition
A while
True
False
Syntax
while condition:
# Do something
Example: Counting with a condition
counter = 1
while counter <= 5:
print("Counting:", counter)
counter += 1
Explanation:
This loop prints numbers from 1 to 5. The variable counter
counter
reaches 6, the condition counter <= 5
False
Controlling loops
Breaking out of a loop with break
break
The break
Example:
for number in range(10):
if number == 5:
break # Exit the loop when number equals 5
print(number)
Output:
0
1
2
3
4
Explanation:
The loop stops when number
Skipping iterations with continue
continue
The continue
Example:
for number in range(5):
if number == 2:
continue # Skip when number equals 2
print(number)
Output:
0
1
3
4
Explanation:
The loop skips printing the number 2 due to the continue
Practical examples
Example 1: Calculating the sum of numbers
total = 0
for number in range(1, 6): # Numbers 1 to 5
total += number
print("Total:", total)
Output:
Total: 15
Explanation:
The loop adds each number from 1 to 5 to the variable total
Example 2: Password check
password = "secret"
attempt = ""
attempts = 0
while attempt != password and attempts < 3:
attempt = input("Enter password: ")
attempts += 1
if attempt == password:
print("Access granted!")
else:
print("Access denied!")
Explanation:
The loop allows up to three attempts to guess the password. If the user enters the correct password within three tries, access is granted. Otherwise, it is denied.
Best practices for using loops
Avoid infinite loops
Ensure that conditions in while
loops will eventually become False
# Avoid this!
while True:
print("This never ends!")
Use descriptive loop variables
Choose variable names that clearly describe their role in the loop.
# Good
for student in students:
print(student)
# Vague
for s in students:
print(s)
Optimize range()
usage
range()
Customize the range()
function with start, stop, and step values.
for i in range(2, 10, 2): # Start at 2, go up to 10, increment by 2
print(i)
Conclusion
Loops are essential tools in programming. They enable you to automate repetitive tasks efficiently, whether by iterating over sequences with for
while
By mastering break
continue