gpt4 book ai didi

python - 如何在 python 的内部 for 循环中中断 while 循环?

转载 作者:太空狗 更新时间:2023-10-30 00:30:14 25 4
gpt4 key购买 nike

while 在 for 循环中 i>10 时不会中断:

i = 0
x = 100
while i<=10:
for a in xrange(1, x+1):
print "ok"
i+=1

并打印 "ok" 100 次。当 for 循环中 i 达到 10 时如何中断 while 循环?

最佳答案

直到内层循环“返回”,外层循环中的条件永远不会被重新检查。如果您需要在每次 i 更改后进行此检查,请改为执行此操作:

while i<=10:
for a in xrange(1, x+1):
print "ok"
i+=1
if i > 10:
break

break 只会退出内循环,但由于外循环条件的计算结果为 False,它也会退出。

关于python - 如何在 python 的内部 for 循环中中断 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13962424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com