Python打破While循环

问题描述 投票:0回答:1

我正在尝试打破Python 3中的while循环

while not at_end()...:
    if ...:
    else:
    code here
    if at_end():
        break

但是,这似乎没有打破while循环。我也尝试过将if放在while循环之后,但是它也不起作用。任何帮助,将不胜感激。

python python-3.x while-loop break
1个回答
0
投票

这似乎应该在for循环中完成。但是,如果需要使用while循环,则可以执行以下操作。

while_flag = True
while while_flag:
    if:
        something
    else:
        something else
    if at_end():
        while_flag = False

0
投票

您通常会这样做:

not_at_end = True
i = 0

while not_at_end:
    if i < 3:
        print('do stuff')
        i += 1
    else:
        print('do other stuff')
        not_at_end = False

# do stuff
# do stuff
# do stuff
# do other stuff

不需要迭代器。重点是在while循环中使用布尔值。

© www.soinside.com 2019 - 2024. All rights reserved.