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

Is python a high level language?

0 Answers  


How to minimize the memcached server outages in your python development?

0 Answers  


How can you create a copy of an object in python?

0 Answers  


What happens when you execute the statement mango=banana in python?

0 Answers  


Does python support inheritance?

0 Answers  






Explain how can you access a module written in python from c?

0 Answers  


Does python supports hybrid inheritance?

0 Answers  


Can a constructor be final?

0 Answers  


Difference between lists and tuples in python?

0 Answers  


What are the key features of Python?

0 Answers  


What is the biggest challenge facing your current job right now? What is your biggest failure?

0 Answers  


Can we concat bytes to str?

0 Answers  


Categories