1

I though I was fully aware of how LEGB rule worked until I came across this. Essentially I am to access the "total" variable within my function local namespace. I know the "total variable is a local namespace but for whatever reason when I try to run this function I get the following error: UnboundLocalError: local variable 'total' referenced before assignment

Example:

total = 0

def two_digit_sum(n):
    for i in str(n):
        total += int(i)
    return total


number = 111
print(two_digit_sum(number))

However when I utilize the following function , I do not come across the error Example:

def spam():
    print(eggs)


eggs = 42
spam()

^^^ As you can see the eggs variable is also a global function.

Paul M.
  • 10,481
  • 2
  • 9
  • 15
Christian
  • 9
  • 3
  • 1
    You can read (and even mutate) variables from outer scopes without having to do anything special, but you can't reassign an outer scope's name. Your first function reassigns `total`, your second function doesn't reassign `eggs`. – Samwise Aug 10 '21 at 21:48
  • 'I know the "total variable is a local namespace"' then I don't think I understand why you are confused. If you remove the line `total = 0`, do you then expect the code to work? What if you had written `total += 0` rather than `total = 0` in the first place? Would you expect that to work if `total` hadn't separately been defined yet? – Karl Knechtel Aug 10 '21 at 22:14
  • @KarlKnechtel, that was a complete typo. I meant to say that I know "total" variable is a global name space – Christian Aug 10 '21 at 22:31
  • Ah, okay. The linked duplicate should answer your question, then. – Karl Knechtel Aug 10 '21 at 22:40
  • @Samwise careful with the word "mutate" in this context. You *can't* mutate *variables* from outer scopes - mutating a variable is generally synonymous with *assigning/re-assigning it*. You can, of course, mutate *objects* that the variable refers to. – juanpa.arrivillaga Aug 10 '21 at 22:56

1 Answers1

0

I think that what you have done is you have given value for total inside the function so you have to make it a global variable.

But in eggs you have done no new value and just printed it.

This code is the solution to you problem.


total = 0

def two_digit_sum(n):
    global total

    for i in str(n):
        total += int(i)
    return total


number = 111
print(two_digit_sum(number))

But if you have given a value of eggs inside the function spam you will get the error.

def spam():
    eggs += 1 
    print(eggs)
    
eggs = 42
spam()

here where you have made a value to it.

Ali Saad
  • 120
  • 8