0

To understand nonlocal and global in Python 3, I read Python nonlocal statement

Also, I read, https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces where in I modified the example a bit with this code:

def scope_test():
    
    def do_global():
        global spam
        print(f'spam: {spam}')
        spam = "global spam"

    spam = "test spam"
    
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)

# spam: global spam
# After global assignment: test spam
# In global scope: global spam

I am not sure, why the first print statement returns 'global spam', but I am also not sure, what ideally it should have returned.

Please help me understand how before assignment of name as 'global spam' print statement was able to write it.

Thanks in advance.

prabh
  • 336
  • 1
  • 3
  • 16
  • 3
    Did you run this in a REPL where you had already been experimenting with the snippet? – Ry- Sep 23 '20 at 19:05
  • @Ry- thanks for the quick reply. I am very new to Python and I now understand that it would have set while I was experimenting with various conditions. Now when I restarted my Jupyter notebook, i got the NameError: name 'spam' is not defined, which is what i expected. Thanks for your quick response. – prabh Sep 23 '20 at 19:10
  • 1
    This raises an error, `NameError: name 'spam' is not defined` – juanpa.arrivillaga Sep 23 '20 at 19:10
  • Voting to close as not reproducible. – Karl Knechtel Sep 13 '22 at 14:51

0 Answers0