Python报UnboundLocalError: local variable 'xxx' referenced before assignment

score_you = 0
def kickedBall(shooter, goalkeeper):
     score_you += 1
kickedBall("myNanme", "com")

执行此代码报UnboundLocalError: local variable 'score_you' referenced before assignment
原因:在函数内部对变量赋值进行修改后,该变量就会被Python解释器认为是局部变量而非全局变量,当程序执行到 score_you = score_you + 1的时候,想当于执行score_you = score_you + 1,此操作是给score_you 赋值,score_you 则被认为是局部变量,此时score_you + 1,解释器在函数内部找不到score_you 的定义,自然报错
解决方式:在函数内部,给变量添加global修饰符,声明此变量为全局变量

score_you = 0
def kickedBall(shooter, goalkeeper):
    global score_you
    score_you += 1
kickedBall("myNanme", "com")

运行,OK

你可能感兴趣的:(Python报UnboundLocalError: local variable 'xxx' referenced before assignment)