我是靠谱客的博主 甜蜜冷风,最近开发中收集的这篇文章主要介绍python终止循环_Python:如果while条件在循环期间发生变化,如何在运行时结束while循环?...,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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.

解决方案

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

...

最后

以上就是甜蜜冷风为你收集整理的python终止循环_Python:如果while条件在循环期间发生变化,如何在运行时结束while循环?...的全部内容,希望文章能够帮你解决python终止循环_Python:如果while条件在循环期间发生变化,如何在运行时结束while循环?...所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部