Python - 在 For 循环中更新变量

标签 python

<分区>

所以我决定用 Python 编写《大富翁》,但我在更新玩家位置时遇到了一些问题。我写了一个 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)

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

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

最佳答案

您有与要更新的目标变量同名的函数参数。 因此,您所做的任何更改都是对函数参数进行的,而不是对全局变量进行的。那是因为 function 为您传递给函数的参数创建了一个本地范围。因此,它掩盖了全局定义的同名变量。

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

关于Python - 在 For 循环中更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14858364/

相关文章:

python - 类中的列表未转储到文件

python - 指定根目录时 gcovr 无限循环

python - 在 python 错误中舍入时间

python - 如何使用python获取原始数据框中扩展/重采样函数的结果

python - 无法在 docker 镜像中导入 cx_Oracle

python - django postgresql 操作错误 : index row size xxx exceeds maximum yyy

python - 无法加载 native TensorFlow 运行时 - TensorFlow 2.1

python - 使用列表理解将 python 中的 4 个列表相交

python - Django 教程。计数器没有变化

python - 具有完整路径名的外部文件上的 os.path.isfile