UnboundLocalError: local variable 'XXX' referenced before assignment solution

1. Example:

Calculate the sum of a to 10

sum=0
def func(a):
    while a<=10:
        sum+=a
        a+=1
    return sum
print(func(9))

operation result:

UnboundLocalError: local variable ‘sum’ referenced before assignment

2. Reason Analysis

If a variable is assigned a value within a scope, then this variable will be considered a local variable, just like within the scope of the func() function, we have reassigned the sum variable: sum+=a, then The compiler will think that the sum variable is a local variable, and this assignment expression is actually performed from right to left, that is to say, when the sum+a operation is performed, sum is not defined, so it explodes Out of this UnboundLocalError error.

Three, the solution

Before assigning a value to sum, use the global keyword to turn sum into a global variable. After setting this way, the compiler will see that sum has been defined outside the function, so it will not report an error.

sum=0
def func(a):
    global sum
    while a<=10:
        sum+=a
        a+=1
    return sum
print(func(8))

Guess you like

Origin blog.csdn.net/YZL40514131/article/details/122082820