[英]While loop in Python not working out
So I just started out with python recently and I tried using a while loop in the code but when I click run, the program just runs forever without printing anything. 因此,我最近刚开始使用python,并尝试在代码中使用while循环,但是当我单击run时,该程序将永远运行,而不会打印任何内容。 I did some research on while loops but I didn't find anything that would help me.
我对while循环进行了一些研究,但没有发现任何对我有帮助的东西。 Here is the code in its entirety:
这是完整的代码:
import random
HeroHP = random.randint(120 , 120)
WitchHP = random.randint(100 , 100)
Alive = 1
Dead = 0
if WitchHP > 0:
WitchStatus = Alive
if WitchHP < 1:
WitchStatus = Dead
if HeroHP > 0:
HeroStatus = Alive
if HeroHP < 1:
HeroStatus = Dead
HeroCritChance = random.randint(0 , 2)
if HeroCritChance == 2:
HeroATK = 25
if HeroCritChance == 0 or FriskCritChance == 1:
HeroATK = 10
WitchHitChance = random.randint(0 , 1)
if WitchHitChance == 0:
WitchATK = 30
if WitchHitChance == 1:
WitchATK = 0
while WitchStatus == Alive and HeroStatus == Alive:
WitchHP = WitchHP - HeroATK
HeroHP = HeroHP - WitchATK
if WitchStatus == Alive and HeroStatus == Dead:
print ("the Hero has been defeated...")
if WitchStatus == Dead and HeroStatus == Alive:
print ("the Hero has triumphed!")
if WitchStatus == Dead and HeroStatus == Dead:
print ("Peace has returned... But at a price...")
(Sorry if I'm making a very silly mistake, as I mentioned earlier, I'm really new to coding in general.) (很抱歉,如果我犯了一个非常愚蠢的错误,就像我之前提到的那样,那么我通常对编码真的很陌生。)
In Python the assignment operation does not work that way. 在Python中,赋值操作无法采用这种方式。
It looks like when you write: 看起来就像在写:
if WitchHP > 0:
WitchStatus = Alive
You think that using WitchStatus
in a future condition it will actually check the value of WitchHP
. 您认为在将来的情况下使用
WitchStatus
实际上会检查WitchHP
的值。 But that's not the case, it does the secuence: first it evaluates the condition, then if that is true it assigns to WitchStatus
. 但这不是事实,它具有安全性:首先它评估条件,然后如果是,它将分配给
WitchStatus
。 If then, the value of WitchHP
changes, the WitchStatus
will not change, unless you run this statement again. 如果这样,
WitchHP
的值将更改,除非再次运行此语句,否则WitchStatus
不会更改。
What you want is a function: 您想要的是一个函数:
def WitchStatus():
if WitchHP > 0:
return Alive
else:
return Dead
while WitchStatus() == Alive:
WitchHP = WitchHP - HeroATK
Then, every time you use the function with WitchStatus()
the program will check the condition again. 然后,每次将函数与
WitchStatus()
,程序都会再次检查条件。
Change this: 更改此:
while WitchStatus == Alive and HeroStatus == Alive:
WitchHP = WitchHP - HeroATK
HeroHP = HeroHP - WitchATK
To an if statement: 对于if语句:
if WitchStatus == Alive.....
In the original, once WitchStatus == Alive, it will remain that way and the loop will keep running because there is nothing that changes it. 在原始版本中,一旦WitchStatus == Alive,它将保持这种方式,并且循环将继续运行,因为没有任何更改。 It's like forgetting to add the i = i + 1 line in a numerically counted loop.
这就像忘记在数字计数循环中添加i = i + 1行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.