Global Local Variables

While printing the value of x which is the global variable we can see the output as 10 getting printed and while using x+=5 we are getting error why?. if by default x was not referencing to global variable then how it was getting printed when we used print(x) inside the function.

x=10
def show():
print(x)
output is 10

but when x+=5 inside function it throw error. Can you please explain in detail.

Hey @Akshay986, let me explain you in detail :

When you use the assignment operator inside any function,… then that variable becomes local to that function only. It does not look for x outside that function. So in this case when you do x = x+1, x becomes local to the inner function and hence error comes up saying that local variable referenced before assignment. So to tell the inner function that x is defined in the outer function, you use the keyword nonlocal .

I hope you get this. You asked a very good question. If you still have even slightest of doubt, refer this link.

Happy Learning :slight_smile:

Thank you for explaining it in detail… Also can you please let me know that ask doubt facility will be available throughout the validity of the course

Yes Yes we are always there to help you out. Even after the course !
Keep Learning and All the best :slight_smile:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.