Python scope question

DL Neil PythonList at danceswithmice.info
Tue Mar 12 14:41:57 EDT 2019


Arup,


On 13/03/19 3:38 AM, Arup Rakshit wrote:
> I have questions how nonlocal and global affecting the variable assignment. Also how each print statement looking up the values for the spam variable. This scope thing in python is very confusing too me still. Can anyone help me to understand this code w.r.t to scope in Python?
...
> $ python3 sample.py
> After local assignment: test spam
> After nonlocal assignment: nonlocal spam
> After global assignment: nonlocal spam
> In global scope: global spam


Think this will help.

Watch the scopes 'appear' and operate in front of your very eyes: 
https://goo.gl/JC6SSh

or
http://pythontutor.com/visualize.html#code=def%20scope_test%28%29%3A%0A%20%20%20%20def%20do_local%28%29%3A%0A%20%20%20%20%20%20%20%20spam%20%3D%20%22local%20spam%22%0A%0A%20%20%20%20def%20do_nonlocal%28%29%3A%0A%20%20%20%20%20%20%20%20nonlocal%20spam%0A%20%20%20%20%20%20%20%20spam%20%3D%20%22nonlocal%20spam%22%0A%0A%20%20%20%20def%20do_global%28%29%3A%0A%20%20%20%20%20%20%20%20global%20spam%0A%20%20%20%20%20%20%20%20spam%20%3D%20%22global%20spam%22%0A%0A%20%20%20%20spam%20%3D%20%22test%20spam%22%0A%20%20%20%20do_local%28%29%0A%20%20%20%20print%28%22After%20local%20assignment%3A%22,%20spam%29%0A%20%20%20%20do_nonlocal%28%29%0A%20%20%20%20print%28%22After%20nonlocal%20assignment%3A%22,%20spam%29%0A%20%20%20%20do_global%28%29%0A%20%20%20%20print%28%22After%20global%20assignment%3A%22,%20spam%29%0A%0Ascope_test%28%29%0Aprint%28%22In%20global%20scope%3A%22,%20spam%29%0A&cumulative=false&curInstr=24&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false


-- 
Regards =dn


More information about the Python-list mailing list