Python Else with Loops
In Python, you can use the else statement with loops. The else block executes when the loop completes normally (without hitting a break statement). This behavior is different from other languages, where else is usually only associated with conditionals.
Here are some common scenarios where you might use the else statement in loops:
- Post-loop processing: You can perform actions after a loop completes if no break occurs.
- Flagging successful iteration: Mark that all loop conditions were met successfully.
What You'll Learn
In this tutorial, you will learn how to use the else statement with loops in Python. You will see how it can execute a block of code after a loop finishes its iterations.
Understanding the else Statement with Loops
The else statement in Python is executed after the loop has completed, but only if the loop wasn't terminated by a break statement. This is useful for cases where you want to handle situations where the loop finishes normally or successfully.
# Example with a for loop and else
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
print("Found 3!")
break
else:
print("Loop completed without a break.")
# Example with a for loop and else
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
print("Found 3!")
break
else:
print("Loop completed without a break.")
In this example, the else block will not run because the loop is interrupted by the break statement. If no break occurs, the else block will execute.
Output:
Found 3!
Found 3!
Example 1: Using else with a for loop
Let's see how the else block behaves when the loop completes normally, without a break:
# Example of else without break
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
else:
print("Loop completed without interruption.")
# Example of else without break
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
else:
print("Loop completed without interruption.")
How It Works:
- for number in numbers:: This starts the loop that will print all numbers from the list.
- else:: Since no break occurred, the else block executes.
Output
1
2
3
4
5
Loop completed without interruption.
1
2
3
4
5
Loop completed without interruption.
Example 2: Using else with a while loop
You can also use the else statement with a while loop. Here’s an example where the loop will only execute the else if it completes normally:
# Example with a while loop
i = 0
while i < 5:
print(i)
i += 1
else:
print("Loop finished without a break.")
# Example with a while loop
i = 0
while i < 5:
print(i)
i += 1
else:
print("Loop finished without a break.")
How It Works:
- while i < 5:: This starts the loop that will run as long as i is less than 5.
- else:: Since no break is triggered, the else block executes after the loop finishes.
Output
0
1
2
3
4
Loop finished without a break.
0
1
2
3
4
Loop finished without a break.
Exercises
Try out the following exercises to practice using the else statement with loops:
1. Write a program that prints all numbers from 1 to 10 and prints "Loop completed!" after the loop finishes.
# Exercise 1: Print numbers and a message after loop
for i in range(1, 11):
print(i)
else:
print("Loop completed!")
# Exercise 1: Print numbers and a message after loop
for i in range(1, 11):
print(i)
else:
print("Loop completed!")
2. Write a program that checks for a number divisible by 5 and prints a message if the loop completes without finding it.
# Exercise 2: Check for a number divisible by 5
numbers = [1, 2, 3, 4, 6, 7, 8]
for number in numbers:
if number % 5 == 0:
print(f"{number} is divisible by 5!")
break
else:
print("No number divisible by 5 found.")
# Exercise 2: Check for a number divisible by 5
numbers = [1, 2, 3, 4, 6, 7, 8]
for number in numbers:
if number % 5 == 0:
print(f"{number} is divisible by 5!")
break
else:
print("No number divisible by 5 found.")
*Tip: Experiment with different loop conditions and see how the else block behaves after each loop!
Frequently Asked Questions
What does else do in a Python loop?
What does else do in a Python loop?
The else block runs only if the loop completes all its iterations without encountering a break. It's useful for post-loop processing or confirming that a condition was never met during iteration.
Can I use else with both for and while loops?
Can I use else with both for and while loops?
Yes, Python allows the use of else with both loop types. It will only run if the loop wasn’t exited early using a break statement.
When is the else block skipped in a loop?
When is the else block skipped in a loop?
The else block is skipped if the loop is interrupted by a break. Otherwise, it executes after the loop finishes iterating normally.
Why use else with loops in Python?
Why use else with loops in Python?
It's useful when searching or scanning values in a loop. If the loop ends without finding a match (and hence without breaking), the else can provide feedback or perform a default action.
Is using else with loops considered good practice?
Is using else with loops considered good practice?
Yes, especially when you want to clearly differentiate between a loop that broke early and one that didn’t. It makes your intentions in the code clearer to readers.
What's Next?
Next, you'll learn about functions in Python, which are reusable blocks of code that help make your programs more organized and efficient. You'll discover how to define and call functions, pass arguments, return values, and understand the benefits of breaking your code into smaller, manageable parts.