Python for循环语句之for-else/while-else

Python for循环语句之for-else/while-else

for

在Python中for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

for i in [1, 2, 3]:
    print(i)

for i in 'Python':
    print(i)
1
2
3
P
y
t
h
o
n

for-else

else语句会在for循环因可迭代对象耗尽的时候执行,但是不会在循环被break语句终止时执行。

在for循环中还有一种情况就是for-else

for i in range(3):
    print('for语句')
else:
    print('else语句')

print('结束for循环')
for语句
for语句
for语句
else语句
结束for循环

在for循环正常执行结束时,会执行else

即使是不进入for循环内部,也会执行else

for i in []:
    print('for语句')
else:
    print('else语句')

print('结束for循环')
else语句
结束for循环

在for循环中执行了break语句而跳出循环时,不会执行else:

for i in range(3):
    if i == 1:
        break  # 增加了break
    print('for语句')
else:
    print('else语句')

print('结束for循环')
for语句
结束for循环

如果for循环中有break语句,但是没有执行,同样会执行else语句:

for i in range(3):
    if i == 10:  # 修改了判断的值
        break
    print('for语句')
else:
    print('else语句')

print('结束for循环')
for语句
for语句
for语句
else语句
结束for循环

可以总结出:

  1. for-else的运行流程不同于if-else:if-else的执行是非此即彼,而for-else更像是else是作为for循环的一部分;
  2. 当循环中出现了break,并且被执行从而将for循环中断时,不执行else;
  3. else只执行一次。

对比

假设我们需要在一个list中找到某个值,并在for循环中做其他操作(如果不需要其他操作,那直接用in即可)

如果不用for-else,我们需要这样实现

flagfound = False
for i in ['java', 'cpp', 'python', 'c#']:
    if i == 'python':
        flagfound = True
        break
    print('执行更多其他的操作')

if not flagfound:
    raise ValueError("List中找不到python字符串")

如果使用for-else:

for i in ['java', 'cpp', 'python', 'c#']:
    if i == 'python':
        break
    print('执行更多其他的操作')
else:
    raise ValueError("List中找不到python字符串")

在第一种情况下,绑定不那么强,需要引入额外变量,并且在维护过程中可能会引入错误。
在第二种情况下,raise它与它所使用的 for 循环紧密绑定,不需要引入额外变量。

while-else

while-else和for-else一样,else语句会在while条件变为False的时候执行,但是不会在循环被break语句终止时执行。

i = 0
while i < 3:
    i += 1
    print('while语句')
else:
    print('else语句')

print('结束while循环')
while语句
while语句
while语句
else语句
结束while循环
while False:
    print('while语句')
else:
    print('else语句')

print('结束while循环')
else语句
结束while循环
i = 0
while i < 3:
    if i == 1:
        break  # 增加了break
    i += 1
    print('while语句')
else:
    print('else语句')

print('结束while循环')
while语句
结束while循环

参考链接:

https://docs.python.org/3/tutorial/controlflow.html?#break-and-continue-statements-and-else-clauses-on-loops

https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops/9980752#9980752

https://www.runoob.com/python/python-for-loop.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ayiya_Oese

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值