简体   繁体   English

Python:如果while条件在循环期间发生变化,如何在while循环运行时结束它?

[英]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 health eventually =0, the loop still continues.我的游戏使用健康,代码以“while health>0:”开始,在游戏的另一个点,当health最终=0时,循环仍然继续。 How do I make the loop end when health=0, without finishing the whole loop.如何在健康 = 0 时结束循环,而不完成整个循环。

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"?当健康= 0 时代码不应该停止,而不是打印“测试”? How to I get it to stop when health=0?当健康= 0时如何让它停止? The code I wrote deducts health based on the users actions, so the times when health=0 can vary.我写的代码根据用户的操作扣除健康,所以健康=0的时间可能会有所不同。 I want to end the code whenever health=0 Any help would be appreciated.我想在 health=0 时结束代码任何帮助将不胜感激。

The condition is only evaluated at the start of each iteration .仅在每次迭代开始时评估条件。 It does not get checked in the middle of an iteration (eg as soon as you set to health to zero).它不会在迭代中间进行检查(例如,一旦您将health设置为零)。

To explicitly exit the loop, use break :要显式退出循环,请使用break

while health>0:
  ...
  if some_condition:
    break
  ...

与 C 中一样, break语句从最小的forwhile循环中跳出。

You should use 'break' statement to come out of the loop您应该使用“break”语句跳出循环

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

Cleaner implementation更清洁的实施

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

Outputs:输出:

You got attacked!
Testing!

In a while loop, you can only get your code to stop if you specify some sort of condition.在 while 循环中,您只能在指定某种条件时停止代码。 In this case, health is always greater than 0, so it keeps printing "you got attacked".在这种情况下,健康总是大于 0,所以它不断打印“你被攻击了”。 You need to make the health variable decrease till it gets to 0 in order to print "test".您需要使健康变量减少直到它变为 0 才能打印“测试”。 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") `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM