Search code examples
pythonglobal-variableslocal-variables

confusion in output of local and global variables in python


I am a newbie to python and was experimenting with local and global variables. 'example1' produced the output '6,16,6 ', which is as expected.

x=6
def example1():
  print x
  print (x+10)
  print x  
example1()

In the 2nd example:

x=6
def example2():
   print x
   print (x+10)
print x  
example2()

I expected '6,16,6' as the o/p, but got '6,6,16 ' as the output. Can someone explain why this happened in 'example2()'?

(I was of the view that the 2nd 'print x' statement in 'example2' is referring to the global variable x (which equals 6), and hence, felt that '6,16,6' should be the output)


Solution

  • In your second example, the first value of x will be 6. Then you are calling the method example2() which will firstly print x ( which is 6 ) and then x+10.

    So the output will be:

    6
    6
    16
    

    For a better understanding, here is the order of execution for your program:

    x=6
    def example2():
       print x
       print (x+10)
    print x  # this will be called first, so the first output is 6
    example2() # then this, which will print 6 and then 16