sandra16
sandra16

Reputation: 73

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)

Upvotes: 0

Views: 80

Answers (3)

Abhishek Kandel
Abhishek Kandel

Reputation: 1

Demonstrate Local and Global Variables.

Local variables are variables that are declared inside a function. Global variables are variables that are declared outside a function.

Program to demonstrate the use of Local and Global Variables.

global_var = 5                     #Global Variable
def add(a,b):
    local_var = a+b                #Local Variable
    print("The sum is",local_var)
    print("The global variable is",global_var)
add(10,20)

Output is:

The sum is 30
The global variable is 5

Upvotes: 0

Dark Matter
Dark Matter

Reputation: 200

x=6
def example2():
   print x +"2nd call"
   print (x+10)
print x+" 1st call"  # This print gets call first
example2()

I think this explains.1st print gets called first as its out of function and before function too If u want output as 6,16,6 make chages as follow

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

Upvotes: 0

user4312749
user4312749

Reputation:

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

Upvotes: 1

Related Questions