Python-在For循环中更新变量

2024-04-28 15:00:24 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我决定用Python编写monopy,但是我在更新播放器位置时遇到了一些问题。我写了一个for循环,循环遍历玩家,为每个人掷骰子,然后更新他们的位置。问题是location变量没有保留最新的位置,它在for循环开始时一直重置回0。这是我的代码:

player1location = 0

def turn(numberPlayers, player, player1location, Board):
    for player in range(numberPlayers):
        player = 'Player'+str(player+1)
        print 'It\'s', player, 'turn!'
        print player1location
        rollDice = raw_input('Press Enter to roll the dice!')
        diceRoll = random.randint(1,6)
        print player, 'rolled a', diceRoll
        player1location = player1location + diceRoll
        print 'You landed on', player1location
        print '\n'

while True:
    turn(numberPlayers, player, player1location, Board)

如果需要的话,我可以提供更多的代码,但我认为这是控制玩家位置的一切。谢谢!

编辑:很明显我是在改变局部变量而不是全局变量。如何更改全局变量?


Tags: 代码boardfor玩家location播放器turn重置
2条回答

您的函数参数与要更新的目标变量同名。 因此,对函数参数而不是全局变量所做的任何更改。这是因为function为传递给函数的参数创建了一个本地作用域。因此,它在全局上覆盖了用相同名称定义的变量。

因此,要么更改函数参数player1location的名称,要么更改全局变量的名称。

注意,您有两个名为player1location的变量,其中一个在第一行(在任何函数之外)全局定义为,第二个在每次调用函数时在本地创建为。尽管它们的名称相同,但它们在python中是两个不同的变量,因为它们是在different scopes中定义的。

有几种方法可以解决这个问题。

您可以从函数定义中删除player1location,然后您将始终更改全局范围的变量。但是,根据命名约定,我猜您也希望将该函数重新用于其他播放器(尽管尝试它仍然不会有什么坏处,可以帮助您理解它是如何工作的)。

更好的方法可能是在函数结束时返回新的播放器位置(return player1location),然后在返回时将其分配给全局范围的位置(player1location = turn(numberPlayers, player, player1location, Board))。

相关问题 更多 >