Python @ DjangoSpin

Making a variable global in Python: global keyword

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Making a variable global in Python

Making a variable global in Python

There will be instances where you are declaring an object inside a confined piece of code, and you will need the object outside it as well. You can use the global keyword for this.

## BEFORE
>>> def storeMyName():
        name = "Ethan"
  
>>> storeMyName()
>>> name
Traceback (most recent call last):
  # Traceback Info
    name
NameError: name 'name' is not defined
 
## AFTER
>>> def storeMyName():
        global name
        name = "Ethan"
  
>>> storeMyName()
>>> name
'Ethan'

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply