Member-only story
Python’s else magic: not just if
Written in front
Mentioning else
always corresponds to an if
. Although this is true in many programming languages, Python is not. Python's else
statement has a wider range of uses. From else
after loop statements to try-except
blocks after else
..., this article will explore the little-known features of else
statements.
1. if-else
Else
can be used with if
, which is also the most commonly used structure. Represents the Code Block executed when the if
condition is not met. For example:
x = 5
if x > 10:
print("x 大于 10")
else:
print("x 不大于 10")
2. for-else
Else
can be used with a for
loop to represent a Code Block executed after the loop ends normally. If the loop is not interrupted by a break
statement, the code in the else
block 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
Else
can be used with try-except
blocks for exception handling. When the code in the try
block does not raise an exception, the code in the else
block is executed; if an exception occurs, the else
block is skipped. For example:
try:
result = 10 / 2
except…