python
Use of else condition with for loop in Python
Else conditional statement can be used with python for loop if the break statement does not execute inside for loop.
#Using else with for loop
for i in range(4):
print(i)
else: # Will execute after loop completed if no break statement
print("I am in else")
#else will not be executed if 'break' executed used inside loop
for item in ['one', 'two', 'three']:
if item == 'two':
break
print(item)
else:
print("This will not be executed")
Output
0
1
2
3
I am in else
one
1
2
3
I am in else
one
Unlike other programming languages, you can use else conditional statement with for loop in python.
In the first code snippet, we are printing the message 'I am in else' when the for loop is completed. If you are using the 'break' keyword inside for loop and it executes inside the for loop then the else conditional statement will not be executed.
Was this helpful?
Similar Posts
- Single line if else condition python
- Use of try, except, else and finally in python
- If else conditions python
- [Python] Use json.dumps() to pretty-print Python dicts
- Use separator in print() method of python
- Learn to Use Python's Built-In String Functions
- Apply condition based multiple filters in SQLAlchemy query