Search code examples
pythonwhile-loopbreak

while loop doesn't stop looping even after variable change


In my code I have to ask users some input. When a condition is met the program should stop running!

ALIVE = True

def you_died():
    global ALIVE
    ALIVE = False

def some_input():
    choice = input()
    if choice == "yes":
        you_died()

while ALIVE is True:
    some_input()
    print("some string")

Why is my code still printing "some string" even though the variable ALIVE is False?

How to break the loop from inside the function?


Solution

  • While conditions are evaluated once per iteration so changing the variable that is used in the condition won't cause it to immediately break. Also, you can't break from within a function. BUT you CAN test your global after calling your function and break if it isn't true before performing any other steps in your while loop:

    ALIVE = True
    
    def you_died():
        global ALIVE
        ALIVE = False
    
    def some_input():
        choice = input()
        if choice == "yes":
            you_died()
    
    while ALIVE is True:
        some_input()
        if not ALIVE: break
        print("some string")