Every Way To Use ‘Else’ in Python
Other than the classic if-else block, we can use the else
keyword in 3 other ways in Python — for-else, while-else & try-else
1) If Else — the classic
fruit = 'orange'
if fruit == 'apple':
print('apple juice')
else:
print('not apple')
- stuff inside the
if
block runs if the condition evaluates to True - stuff inside the
else
block runs if the condition evaluates to False
2) For Else
for i in range(5):
# do stuff
else:
print('this runs if break DOES NOT happens in above for loop')
In a for-else block, stuff in the else
block runs only if the break
statement DOES NOT run inside the for loop.
for i in range(5):
print(i)
if i == 2:
break
else:
print('else block runs')
# 0 1 2
^ here, range(5)
generates 0 1 2 3 4
, and break
happens when i==2.
Since break
happens inside the for loop, the else
block does not run.
for i in range(5):
print(i)
if i == 100:
break
else:
print('else block runs')
# 0 1 2 3 4
# else block runs
^ here, i==100 does not happen, and break
does not run.
Since break
does not run, else
block runs.
3) While Else
while condition:
# do stuff
else:
print('else block runs if break DOES NOT run in while loop')
This functions the same way as the for-else block.
- If
break
happens,else
does not happen - If
break
does not happen,else
happens
4) Try Else
try:
# stuff
except Exception as e:
print(e)
else:
print('else block runs if except block DOES NOT run')
- if
except
happens,else
does not happen - if
except
does not happen,else
happens
try:
x = 1/0
except Exception as e:
print('except block runs ->', e)
else:
print('else block runs')
# except block runs -> division by zero
^ here, 1/0
forces the ZeroDivisionError, which forces the except
block to run. As the except
block runs, the else
block does not run.
try:
x = 1/1
except Exception as e:
print('except block runs ->', e)
else:
print('else block runs')
# else block runs
^ here, 1/1
does not cause an Exception. The except
block does not run, so the else
block runs.
Conclusion
I hope this was helpful in some way
If You Wish To Support Me As A Creator
- Clap 50 times for this story
- Leave a comment telling me your thoughts
- Highlight your favourite part of the story
Thank you! These tiny actions go a long way, and I really appreciate it!
YouTube: https://www.youtube.com/@zlliu246
LinkedIn: https://www.linkedin.com/in/zlliu/
My Ebooks: https://zlliu.co/ebooks