Else Clause in for and while Loops (Python)
In Python, the else clause can be used not only with if statements but also with for and while loops.
Syntax
while/for (condition):
block1
else:
block2
What is the purpose of the else clause in a loop?
In an iterative structure, the else clause specifies the code to execute once the loop completes all its iterations.
This block runs after the loop finishes its last iteration.
Example
The else clause in loops is a unique feature of Python.
It's not found in other programming languages like C or Java, where else is only used in conditional control structures.
In Python, you can use the else clause in both for and while loops.
Note: If the loop is prematurely terminated with a break statement, the else clause is not executed because the loop exits due to the forced termination.
Practical Examples
Here are some practical examples of using the else clause in Python's looping structures.
Example 1 (for)
In this script, a for loop iterates 5 times.
- for x in range(1, 6):
- print(x)
- else:
- print("end")
After the fifth iteration, the for loop executes the else clause.
The program output is:
1
2
3
4
5
end
The else clause is executed after the last iteration of the loop.
It's like a final additional step.
Example 2 (while)
In this second script, a while loop runs for 5 iterations.
- x = 1
- while (x < 6):
- print(x)
- else:
- print("end")
At the end of the fifth iteration, the while loop executes the else clause.
The program output is:
1
2
3
4
5
end
The functionality of the else clause is essentially the same in both for and while loops.
And so on.