简体   繁体   中英

Python Breaking While Loop

I am trying to break out of a while loop in Python 3

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

However, this does not seem to break the while loop. I have also tried putting the if right after while loop, but it does not work either. Any help would be appreciated.

This looks like it should've been done in a for loop. But if it needs to be a while loop you can do something like this.

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

You would typically do it like:

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

The iterator (i) is just to show example code. The main point is to use a boolean to break the while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM