Python:如果while条件在循环期间发生变化,如何在while循环运行时结束它? [英] Python: How to end a while loop while it is running if the while condition changes during the loop?

查看:51
本文介绍了Python:如果while条件在循环期间发生变化,如何在while循环运行时结束它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些关于我正在尝试制作的基于文本的游戏中的代码的帮助.我的游戏使用健康,代码以while health>0:"开始,在游戏的另一个点,当health最终=0时,循环仍然继续.如何在健康 = 0 时结束循环,而不完成整个循环.

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.

这是一个例子:

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

代码不应该在 health=0 时停止,并且不打印test"吗?当健康= 0时如何让它停止?我写的代码根据用户的操作扣除健康,所以健康=0的时间可能会有所不同.我想在 health=0 时结束代码 任何帮助将不胜感激.

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.

推荐答案

条件仅在每次迭代开始时评估.它不会在迭代中间检查(例如,一旦您将 health 设置为零).

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

要显式退出循环,请使用 break:

To explicitly exit the loop, use break:

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

这篇关于Python:如果while条件在循环期间发生变化,如何在while循环运行时结束它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆