Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading