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

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

What is range() in python?

436


What is a method call?

429


How do you sort values in descending order in python?

451


How manages to python handle memory management?

455


What is a function for flatten an irregular list of lists?

454






What is monkey Patching in python?

556


What is python rest api?

446


What is anonymous function or lambda function?

459


Explain the use of // operator in python?

469


Is python zero indexed?

444


What is the use of dir() function?

457


What is the difference between locals() and globals ()?

419


How do I publish a package in python?

448


What do you understand of pep 8?

456


How to make a chain of function decorators?

447