What are the rules for local and global variables in Python?



What are the rules for local and global variables in Python?..

Answer / chaitanya

If a variable is defined outside function then it is implicitly global. If variable is assigned new value inside the function means it is local. If we want to make it global we need to explicitly define it as global. Variable referenced inside the function are implicit global. Following code snippet will explain further the difference

#!/usr/bin/python

# Filename: variable_localglobal.py

def fun1(a):

print 'a:', a

a= 33;

print 'local a: ', a

a = 100

fun1(a)

print 'a outside fun1:', a

def fun2():

global b

print 'b: ', b

b = 33

print 'global b:', b

b =100

fun2()

print 'b outside fun2', b

-------------------------------------------------------

Output

$ python variable_localglobal.py

a: 100

local a: 33

a outside fun1: 100

b :100

global b: 33

b outside fun2: 33

Is This Answer Correct ?    1 Yes 0 No

Post New Answer

More Python Interview Questions

What is the common way for the flask script to work?

0 Answers  


What is sphinx python?

0 Answers  


What is a CGI script in Python?

0 Answers  


Is python sorted stable?

0 Answers  


What is print format value interpolation?

0 Answers  


Explain logical operators in python?

0 Answers  


What is the output of the below code?

0 Answers  


Which is better PHP or Python?

0 Answers  


What is the use of the // operator?

0 Answers  


Name few python web frameworks for developing web applications?

0 Answers  


What exactly is SVM?

2 Answers  


What is composition in python?

0 Answers  


Categories