Python成功解决 UnboundLocalError: local variable ‘xxx‘ referenced before assignment

scores = {'语文':89, '数学':95, '英语':80}
sum_score = 0 
def get_average(scores):
    for subject, score in scores.items():
        sum_score += score
        print('现在的总分是%d'%sum_score)
    ave_score = sum_score/len(scores)
    print('平均分是%d'%ave_score)

get_average(scores)

错误类型

UnboundLocalError: local variable ‘xxx’ referenced before assignment

解决方案

把变量声明称global,global sum_score

scores = {'语文':89, '数学':95, '英语':80}
sum_score = 0 


def get_average(scores):
    global sum_score 
    for subject, score in scores.items():
        sum_score += score
        print('现在的总分是%d'%sum_score)
    ave_score = sum_score/len(scores)
    print('平均分是%d'%ave_score)

get_average(scores)
#print(scores.items())
#for subject, score in scores.items():
#    print('{} and {} and {}'.format(subject,score,type(score)))
#    sum_score += score
#    print(sum_score)

说明这个错误类型

如果我们在函数内部命名了函数外的变量,会引起歧义。

number = 6
def add():
    number =number+7
    return number
m=add()
print(m)

计算机认为变量正在定义,怎么直接用上了?,会报错
报错UnboundLocalError: local variable 'number' referenced before assignment

我们需要告诉计算机,这个变量number不是函数内的原住民,他是外来变量。

number = 6
def add():
    global number
    number =number+7
    return number
m=add()
print(m)

然后,我们删除掉return,看看结果是怎么样的?

number = 6
def add():
    global number
    number =number+7
    #return number
print(number)
m=add()
print(m)
print(number)

如果我们不调用函数,则函数是不会运行的,number打印结果还是原来的的数字。

6
None
13

你可能感兴趣的:(#,Python,python,bug,变量作用域问题)