Member-only story

Python’s else magic: not just if

Beck Moulton
2 min readMay 10, 2024

--

Written in front

Mentioning elsealways corresponds to an if. Although this is true in many programming languages, Python is not. Python's elsestatement has a wider range of uses. From elseafter loop statements to try-exceptblocks after else..., this article will explore the little-known features of elsestatements.

1. if-else

Elsecan be used with if, which is also the most commonly used structure. Represents the Code Block executed when the ifcondition is not met. For example:

x = 5
if x > 10:
print("x 大于 10")
else:
print("x 不大于 10")

2. for-else

Elsecan be used with a forloop to represent a Code Block executed after the loop ends normally. If the loop is not interrupted by a breakstatement, the code in the elseblock is executed. For example:

fruits = ['苹果', '香蕉', '橙子']
for fruit in fruits:
if fruit == '橙子':
break
print(fruit)
else:
print("没有循环被中断")

It should be noted that if the for loop ends normally, the else code will not be executed

3. try-except-else

Elsecan be used with try-exceptblocks for exception handling. When the code in the tryblock does not raise an exception, the code in the elseblock is executed; if an exception occurs, the elseblock is skipped. For example:

try:
result = 10 / 2
except…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet