简体   繁体   中英

Why Can't I break out of the loop?

Python beginner here. Sorry if it's a basic python concept

over = False

def run():
    user_input = input("Over? (y/n): ")
    if(user_input == 'y'):
        over = True

while not over:
    run()

Although the input is 'y' the loop doesn't stop.

You need to write global over , so function run() will change global variable

over = False

def run():
    global over
    user_input = input("Over? (y/n): ")
    if(user_input == 'y'):
        over = True

while not over:
    run()

You shouldn't be using a global variable here. Return a boolean, and call run as the condition of the loop. (At this point, you may want to reconsider the name run as well.)

def run():
    user_input = input("Over? (y/n)")
    return user_input == 'y'

while run():
    ...

You are setting the local variable over inside the function run() , but you aren't passing it out to the scope from which it was called. Instead return the value to the calling scope like this:

over = False

def run():
    user_input = input("Over? (y/n): ")
    if(user_input == 'y'):
        over = True
    else:
        over = False
    return over

while not over:
    over = run()

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