Python: How To End A While Loop While It Is Running If The While Condition Changes During The Loop?
I need some help with code in a text based game I am trying to make. My game uses health, and the code starts off with 'while health>0:', and in another point in the game, when
Solution 1:
The condition is only evaluated at the start of each iteration. It does not get checked in the middle of an iteration (e.g. as soon as you set to health
to zero).
To explicitly exit the loop, use break
:
while health>0:
...
if some_condition:
break
...
Solution 2:
Solution 3:
You should use 'break' statement to come out of the loop
health=100
while health>0:
print("You got attacked")
# decrement the variable according to your requirement inside the loop
health=health-1
if health==0:
breakprint("test")
Solution 4:
Cleaner implementation
health = 100whileTrue:
if (health <= 0): breakprint ("You got attacked!")
health = 0print ("Testing!")
Outputs:
You got attacked!
Testing!
Solution 5:
In a while loop, you can only get your code to stop if you specify some sort of condition. In this case, health is always greater than 0, so it keeps printing "you got attacked". You need to make the health variable decrease till it gets to 0 in order to print "test". Hence;
` health=100
while health>0:
print("You got attacked")
health-=5
if health==0:
print("test")
break`
An alternative could be this also;
` health=100
if health>0:
print("You got attacked")
if health==0:
print("test") `
Post a Comment for "Python: How To End A While Loop While It Is Running If The While Condition Changes During The Loop?"