使用Python更改函数内函数外部创建的变量

使用Python更改函数内函数外部创建的变量,python,variables,Python,Variables,我试图更改在函数determineWinner之外创建的player_score、cpu_score和ties的值,但出现如下错误: UnboundLocalError:分配前引用的局部变量“cpu\U分数”。我已经删除了其他作业(player_score=player_score+1和ties=ties+1),并添加了打印(“player score”,player_score)来测试程序 我不明白这是为什么 打印(“玩家分数”,玩家分数)输出函数外指定的值,但 cpu_分数=cpu_分数+1

我试图更改在函数determineWinner之外创建的player_score、cpu_score和ties的值,但出现如下错误: UnboundLocalError:分配前引用的局部变量“cpu\U分数”。我已经删除了其他作业(player_score=player_score+1和ties=ties+1),并添加了打印(“player score”,player_score)来测试程序

我不明白这是为什么 打印(“玩家分数”,玩家分数)输出函数外指定的值,但 cpu_分数=cpu_分数+1产生“分配前引用”错误

showRolls也做了它应该做的事情

函数似乎可以读取函数外部指定的变量值,但不能更改值。为什么呢

import random

def showRolls():
    print("Player 1 roll:",player_roll)
    print("CPU roll:",cpu_roll)

def determineWinner():
    if player_roll > cpu_roll:
        print("Player wins!")
        print ("Player Score",player_score)
    elif cpu_roll > player_roll:
        print("CPU wins!")
        cpu_score=cpu_score+1
    else:
        print("It's a tie.")

#-----------------------MAIN PROGRAM------------------------------------
player_score=0
cpu_score=0
ties=0
player_roll = random.randint(1,6)
cpu_roll = random.randint(1,6)
showRolls()
determineWinner()

在函数中,将函数外部以及您要更改的所有变量声明为
global
。读取全局变量不需要声明。有一些解释

因此,您的功能应该是:

def determineWinner():
    global cpu_score
    if player_roll > cpu_roll:
        print("Player wins!")
        print ("Player Score",player_score)
    elif cpu_roll > player_roll:
        print("CPU wins!")
        cpu_score=cpu_score+1
    else:
        print("It's a tie.")

请阅读python的LEGB范围规则。虽然你可以解决这个问题,但这可能是个坏主意。您可能想考虑将它封装在类中,或者将参数传递给函数并返回值。全局变量是不好的。还有十几个问题更直接地说是dup of…但它们都是dup of,所以我想这是规范的版本。如果不清楚这是怎么一回事,点击几十个链接和相关问题中的几个;其中大约一半与此相同。不!!!!为什么人们总是建议使用Globals-please-Globals很少是正确的解决方案,而在这里,它们肯定不是。这里正确的解决方案是将数据封装在一个类中。Globals是很难找到的bug的来源,应该积极劝阻。@TonySuffolk66:请原谅,虽然我非常同意你的anit global咆哮,但OP问他们的代码为什么不工作,这就是答案。没有人建议或建议使用globals,其他人已经发表评论阻止使用globals。为语气道歉:-)我只是看到globals和颤栗:-(