[Chennaipy] Python interpreter

Sharmila Gopirajan sharmila.gopirajan at gmail.com
Fri Jul 1 13:42:03 EDT 2016


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 <ammaranjith at gmail.com>
> To: chennaipy at python.org
> Subject: [Chennaipy] Python interpreter
> Message-ID:
>         <CABYszAQvLewo8qj_dBr5iP=
> j5V4PK3iaTDYJSuSafHnpVU_j6g at 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 at python.org
> https://mail.python.org/mailman/listinfo/chennaipy
>
>
> ------------------------------
>
> End of Chennaipy Digest, Vol 35, Issue 1
> ****************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chennaipy/attachments/20160701/c0c4700c/attachment.html>


More information about the Chennaipy mailing list