Home »
Python
else with for/while statement in Python
Last Updated : April 22, 2025
As we know that else can be used with if statement in Python and other programming languages (like C, C++, Java, etc).
Python else with for/while
In Python, we can use else with for/while to determine whether for/while loop is terminated by a break statement or not i.e. else statement used with for/while is executed only when for/while is not terminated by break statement.
Syntax
The syntax of the else statement with for/while is:
while condition:
# returning True or False
STATEMENTs BLOCK 1
else:
# optional part of while
STATEMENTs BLOCK 2
For TARGET- LIST in EXPRESSION-LIST:
STATEMENT BLOCK 1
else: # optional block
STATEMENT BLOCK 2
Practice the below-given examples to understand the concept of using the else statement with a while/for loop.
Example 1: Else with For/While Loop Without Break
Here, we are demonstrating the use of the else statement with both for and while loops, where the else block is executed only when the loop completes without being interrupted by a break statement.
# python program to demosntrate
# example of "else with for/while"
# using else with for
for num in range(1, 10):
print(num)
else:
print("Full loop successfully executed")
# using else with while
string = "Hello world"
counter = 0
while(counter < len(string)):
print(string[counter])
counter += 1
else:
print("Full loop successfully executed")
Output
1
2
3
4
5
6
7
8
9
Full loop successfully executed
H
e
l
l
o
w
o
r
l
d
Full loop successfully executed
Example 2: Else with For/While Loop with Break
Here, we are demonstrating the use of the else statement with both for and while loops, where the else block is skipped if the loop is terminated early by a break statement.
# python program to demosntrate
# example of "else with for/while"
# using else with for
for num in range(1, 10):
print(num)
if(num==5):
break
else:
print("Full loop successfully executed")
# using else with while
string = "Hello world"
counter = 0
while(counter < len(string)):
print(string[counter])
if string[counter] == ' ':
break
counter += 1
else:
print("Full loop successfully executed")
Output
1
2
3
4
5
H
e
l
l
o
Consider both of the above examples, when we used a break statement – else statement is not executed and we didn't use break statement – else statement is executed.
Python Pass Statement Exercise
Select the correct option to complete each statement about the pass statement in Python.
- The pass statement is used to ___ a block of code where a statement is syntactically required but no action is needed.
- The pass statement is commonly used in ___ blocks, like when defining an empty function or class.
- The pass statement does not ___ the flow of execution in the program.
Advertisement
Advertisement