-3
x = 5
def foobar():
    print (x) #Prints global value of x, which is 5
    x = 1 #assigns local variable x to 1
foobar()

Instead, it throws a

UnboundLocalError: local variable 'x' referenced before assignment

What am I misunderstanding in the comments? Note, I understand if i do x=x+1, it'll throw error due to 'accessing value of local scope x beforei it's defined', but in this case I'm doing x=1, which does not require reading of existing value of x! This is NOT a duplicate question.

user1008636
  • 2,989
  • 11
  • 31
  • 45
  • 2
    If you have complaints about the duplicate closure, please discuss it in the comments. Reposting your question with a *"This isn't a dupe"* addendum isn't productive. – Aran-Fey Aug 14 '18 at 21:20
  • 1
    The error is coming from `print(x)` which uses the value of `x` before it is defined, not `x = 1`. The `x = 1` makes the variable local to the function; therefore, it doesn't have a value when `print(x)` is executed. – kindall Aug 14 '18 at 21:34
  • "but in this case I'm doing x=1, which does not require reading of existing value of x!" But you're doing it **after `print(x)`**, which **does**. You would realize this by **reading the [complete](https://meta.stackoverflow.com/questions/359146) error message**, which shows a stack trace, indicating the line where the problem occurs. This is absolutely a duplicate. – Karl Knechtel Sep 09 '22 at 12:29

1 Answers1

1

If you want to change a global variables value in a function in python, you have to do

x = 5
def foobar():
    global x
    print (x) #Prints global value of x, which is 5
    x = 1 #assigns local variable x to 1
foobar()
Haris
  • 12,120
  • 6
  • 43
  • 70
  • Thanks, but what is the explanation for the error in my code? – user1008636 Aug 14 '18 at 21:19
  • @user1008636 The error you get is explained in the first answer to the first duplicate of your previous question. – Thierry Lathuille Aug 14 '18 at 21:23
  • The use of `global ...` is discouraged when used multiple times as it can be tricky to keep track and mange functions that are modifying global or local variables. Passing the variable as a parameter is preferred – N Chauhan Aug 14 '18 at 21:26
  • @user1008636, just to give you a clear view on how this happens (https://i.imgur.com/xkF6PKA.png), when the interpreter knows there will be assignments to a variable all the lookups on that variable are done from the local scope (LOAD_FAST). – John Smith Aug 14 '18 at 21:33