python中的`else`在for、while、try 语句的使用方法
for ... else ...
当for
循环执行完时, 且该for
循环没有被 break
语句终止,才运行 else
语句
Eg:
for i in range(1, 5):
if i == 4:
print("Not break")
else:
print("Run else")
"""输出
Not break
Run else
"""
for i in range(1, 5):
if i == 4:
print("break")
break
else:
print("Run else")
"""输出
Not break
"""
while ... else ...
与for
循环类似;当while循环执行完时,且未被break
语句终止,才运行else
语句
Eg:
i = 0
while i <= 5:
i += 1
if i == 4:
print("Not break")
else:
print("Run else")
"""输出
Not break
Run else
"""
i = 0
while i <= 5:
i += 1
if i == 4:
print("break")
break
else:
print("Run else")
"""输出
break
"""
try ... else ...
当 try
语句块中没有异常抛出时,才运行else
语句,else
语句抛出的异常不会由前面的except
语句处理。
(~﹃~)~zZ
???
t