Python: How to end a while loop while it is runnin

2020-05-07 01:13发布

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 health eventually =0, the loop still continues. How do I make the loop end when health=0, without finishing the whole loop.

Here is an example:

health=100
while health>0:
  print("You got attacked")
  health=0
  print("test")

Should the code not be stopping when health=0, and not print "test"? How to I get it to stop when health=0? The code I wrote deducts health based on the users actions, so the times when health=0 can vary. I want to end the code whenever health=0 Any help would be appreciated.

4条回答
手持菜刀,她持情操
3楼-- · 2020-05-07 01:25

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:
    break
  print("test")
查看更多
Anthone
4楼-- · 2020-05-07 01:37

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
  ...
查看更多
霸刀☆藐视天下
5楼-- · 2020-05-07 01:43

Cleaner implementation

health = 100
while True:
    if (health <= 0): break
    print ("You got attacked!")
    health = 0
    print ("Testing!")

Outputs:

You got attacked!
Testing!
查看更多
登录 后发表回答