Python中的else用法:不止是if
1. if-else
else 可以与 if 一起使用,这是最常用的一种结构。表示在 if 条件不满足时执行的代码块。
x = 5
if x > 10:
print("x 大于 10")
else:
print("x 不大于 10")
2. for-else
else 可以与 for循环一起使用,表示在循环正常结束后执行的代码块。如果循环中没有遇到 break 语句中断循环,则执行 else 块中的代码。
需要注意:如果for循环正常结束就不会执行else代码
fruits = ['苹果', '香蕉', '橙子']
for fruit in fruits:
if fruit == '香蕉':
break
print(fruit)
else:
print("没有循环被中断")
3. try-except-else
else 可以与异常处理的 try-except 一起使用。当 try 块中的代码没有引发异常时,执行 else 块中的代码;如果发生异常,则跳过 else 块。
注意:只用不发生异常才会执行else语句
try:
result = 10 / 2
except ZeroDivisionError:
print("除数不能为零")
else:
print("计算结果:", result)
4. while-else
else 可以与 while 循环一起使用,表示在循环条件不满足时执行的代码块。当循环条件为 False 时,执行 else 块中的代码。
注意:while循环结束执行else语句
count = 0
while count < 5:
print(count)
count += 1
else:
print("循环结束")
5. with-else
else 可以与 with 语句一起使用,用于在资源管理方面的情况下执行清理操作。else 块中的代码将在 with 块正常结束后执行。
注意:如何产生异常,则不会执行else语句
with open("file.txt", "r") as file:
content = file.read()
# 执行文件操作
else:
print("文件操作完成")

浙公网安备 33010602011771号