Python中else除了可以与if组成条件语句外,还可以和while 、for 、try一起串联使用。
else和while配合使用:
count=0
while count>12:
if (11>0):
print("成立")
break
count+=1
else:
print(‘不成立‘) #当while条件不成立,直接跳到该处输出
else和for配合使用:
def forelse():
c = [1,2]
for i in c:
print(i)
else:
print("输出") #当for循环结束会输出该语句
else和try配合使用:
def tryelse():
try:
sum = 1+1
except TypeError as e:
print("报错")
else:
print("到我这里了") #当try块中的语句正常执行完毕会执行该方法。
原文:https://www.cnblogs.com/tianrunzhi/p/10393696.html