1

Hello I am newbie to Python. While learning I came across below code snippets in that I am unable to understand behaviour of the code. Here is first case

#Case 1
x=1
def func():
    x=5
    print(x)

func()
5

Here is second case

#Case 2  
x=1
def func():
    print(x) #First print statement
    x=5
    print(x) #Second print statement

func()
UnboundLocalError: local variable 'x' referenced before assignment

The two cases are same except the second has one additional print statement. Why the first print statement of second snippet making the Python to throw an exception?

2
  • I thought the first print statement in second case will print value of global variable x i.e 1 and the second will print value of local x i.e 5. BTW thanks for your answer. Commented Apr 18, 2015 at 15:23
  • Thanks Simeon! Now I understood. Commented Apr 18, 2015 at 15:26

1 Answer 1

3

The x outside the function is there but x is also defined in both functions as a local variable and you must define it before using it. It doesn't mean that Python will use the x from outside the function first and then allow you to redefine x as a local variable and then use the local variable x in the rest of the function.

So the difference is really between:

def func():
    x=5
    print(x)

def func():
    print(x) #First print statement
    x=5
    print(x) #Second print statement

In both functions x is a local variable but in the second function you're trying to use it before it's being defined in that function. Hence the error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.