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

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

问题描述

在我尝试制作的基于文本的游戏中,我需要一些代码方面的帮助.我的游戏使用运行状况,并且代码从"while health> 0:"开始,在游戏的另一点,当health最终= 0时,循环仍然继续.当health = 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"?当health = 0时如何停止?我编写的代码会根据用户的操作推断健康状况,因此health = 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天全站免登陆