Python using global variables in functions

 

To use globally defined variable in a python function we need to call it with global keyword before using it.

The keyword global is only useful to change or create global variables in a local context.

To be more precise lets try with 2 examples.

In this example I will show how a variable behaves without global:

strVar = 'a'
def ourFuction():
  strVar = 'z'
  print "In ourFunction : " + strVar
ourFuction()
print "After ourFunction : " + strVar

Output:

In ourFunction : z
After ourFunction : a

In this example I will show how a variable behaves by using global:

strVar = 'a'
def ourFuction():
  global strVar
  strVar = 'z'
  print "In ourFunction : " + strVar
ourFuction()
print "After ourFunction : " + strVar

Output:

In ourFunction : z
After ourFunction : z

Just observe two outputs, in first example since we are not used global we got two different outputs for same variable “str”, where as in second variable we used global in our function definition, so we got same output.

With above 2 example we can clearly distinguish between global and local variables.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s