Python:从被调用的模块内部循环中更改while循环的条件值

时间:2013-08-27 23:39:16

标签: python loops while-loop

我希望通过action()模块中的if语句改变我的while循环条件(而repeat为True)的变量(重复= 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

1 个答案:

答案 0 :(得分:2)

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

def action():
    global repeat