Skip to content

Instantly share code, notes, and snippets.

@yangshun
Created November 26, 2014 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yangshun/f99d00cb467890bdb849 to your computer and use it in GitHub Desktop.
Save yangshun/f99d00cb467890bdb849 to your computer and use it in GitHub Desktop.
Demonstrate local, nonlocal, and global scope of variables
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam) # test spam
do_nonlocal()
print("After nonlocal assignment:", spam) # nonlocal spam
do_global()
print("After global assignment:", spam) # nonlocal spam
scope_test()
print("In global scope", spam) # global spam
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment