0

我希望通过正在调用的 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
4

1 回答 1

2

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

def action():
    global repeat 
于 2013-08-27T23:43:19.077 回答