• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: while loop doesn’t stop looping even after variable change

Resolved: while loop doesn’t stop looping even after variable change

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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?

Answer:

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")

If you have better answer, please add a comment about this, thank you!

break python while-loop
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Is pandas groupby() function always produce a DataFrame with the same order respect to the column we group by?

24/03/2023

Resolved: Kivy widget hierarchy not behaving as expected

24/03/2023

Resolved: Pandas Groupby Get Values from Previous Group

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.