在Python中的while或者for循环之后还可以有else子句,作用是for循环中if条件一直不满足,则最后就执行else语句。
for i in range(5):
if i > 3:
print(i)
else:
print('hello world')
#输出
4
hello world
可以看到上面的for
循环走完之后,会执行下面else
语句。
下面稍微改变一下:
for i in range(5):
if i > 3:
print(i)
break
else:
print('hello world')
# 输出
4
在for
循环中加了个break
后,循环会在if
条件满足时退出,后面的else
语句不执行。
while
语句也是如此:
i = 0
while i < 3:
print(i)
i += 1
else:
print('hello world')
# 输出
0
1
2
hello world
#############################
i = 0
while i < 3:
if i > 1:
print(i)
break
i += 1
else:
print('hello world')
# 输出
2