【问题标题】:Python: Change condition value of while loop from called module inside loopPython:从循环内的被调用模块更改while循环的条件值
【发布时间】: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 == Trueif something == False。使用if somethingif not something,或者如果您真的想检查该值是否是规范的TrueFalse 对象,请使用if something is Trueif something is False
  • 胡安的回答解决了我问的问题,但感谢您提供这些信息,我会相应地更新。
  • 解释:在布尔上下文中,非空容器、非零数字和大多数其他不具有类似零值的对象被认为是真的,但== True 将报告False。另外,由于历史原因,1 == True,所以即使你真的关心值是否是对象True== 也不起作用。您必须使用is 来检查对象身份。

标签: python loops while-loop


【解决方案1】:

您必须将repeat 声明为全局变量才能从action() 内部更改它。在 def action() 之后包含这一行:

def action():
    global repeat 

【讨论】:

  • 请记住,如果您从函数内部修改全局变量,则必须将其声明为全局变量。如果您只是添加变量,则无需使用全局。
猜你喜欢
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
  • 2018-07-24
  • 2011-12-08
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
相关资源
最近更新 更多