【发布时间】:2013-08-28 07:48:46
【问题描述】:
我希望通过 action() 模块中的 if 语句更改我的 while 循环条件的变量(while repeat 为 True)(repeat = False,因此不满足 while 循环的条件)在 while 循环本身内被调用。 评论应始终解释我的意图。
注意这是我实际工作的较大代码的简化版本。希望我能够简单明了地表达我的观点,而不会像我在其他帖子中遇到的那样增加令人困惑的代码。
# Defining the variables
repeat = True
class monster:
hp = 5
class fighter:
damage = 1
# Defining my action module
def action():
monster.hp -= fighter.damage # Monster's hp decreases by fighter's damage
print "Monster HP is %s" % monster.hp # Print this result
if monster.hp < 1: # Check to see if monster is dead, hp less than 1
repeat = False # If monster is dead, stop repeating
else:
repeat = True # If monster is not dead, repeat attack
# Here is the while loop
while repeat is True: # Defining the condition for the while loop
print "repeat is %r" % repeat # Here it should print repeat is True
action() # Then call the action module
print "repeat is %r" % repeat # Here it should print repeat is False
【问题讨论】:
-
不,不,不! 从不使用
if something == True或if something == False。使用if something或if not something,或者如果您真的想检查该值是否是规范的True或False对象,请使用if something is True或if something is False。 -
胡安的回答解决了我问的问题,但感谢您提供这些信息,我会相应地更新。
-
解释:在布尔上下文中,非空容器、非零数字和大多数其他不具有类似零值的对象被认为是真的,但
== True将报告False。另外,由于历史原因,1 == True,所以即使你真的关心值是否是对象True,==也不起作用。您必须使用is来检查对象身份。
标签: python loops while-loop