the variable 'x' defined outside the scope of the function f is a global variable. Python allows access of the global variable within the function.
But when you assign the value x=5, it starts to treat x as a local variable. When there is a print statment before the assignment, you get unbound local error. x = 1 def f(): x = 5 print (x) f () #prints 5 print (x) #prints 1 In the above case, there is a global variable x and there is also a local variable x. Assigning to the local variable, does not change the global variable x. If you do want to modify the global variable, you need to explicitly tell the interpreter that you would like to work with the global variable. x = 1 def f(): global x x = 5 print (x) f () #prints 5 print (x) #prints 5 Date: Fri, 1 Jul 2016 16:57:48 +0530 > From: ranjith pillay <ammaranj...@gmail.com> > To: chennaipy@python.org > Subject: [Chennaipy] Python interpreter > Message-ID: > <CABYszAQvLewo8qj_dBr5iP= > j5v4pk3iatdyjsusafhnpvu_...@mail.gmail.com> > Content-Type: text/plain; charset="utf-8" > > Hello friends, > > I have a question to ask. > > If you define the following cases: > > Case 1: > ----------- > x = 1 > def f(): > print(x) > > Case 2: > ----------- > x = 1 > def f(): > print(x) > x = 5 > print(x) > > > If you call the function f, in case 1 there won't be a problem, It will > print 1. But in case 2, it will give an error "UnboundLocalError: local > variable 'x' referenced before assignment"...One would think that in case > 2, it should have printed 1 and 5. Any one could explain what is happening > here? Why does the interpreter get confused in the 2nd Case? > > Thanks. > > Regards, > Ranjith > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/chennaipy/attachments/20160701/8073650d/attachment-0001.html > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Chennaipy mailing list > Chennaipy@python.org > https://mail.python.org/mailman/listinfo/chennaipy > > > ------------------------------ > > End of Chennaipy Digest, Vol 35, Issue 1 > **************************************** >
_______________________________________________ Chennaipy mailing list Chennaipy@python.org https://mail.python.org/mailman/listinfo/chennaipy