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 the most "pythonic" way to iterate over a list in chunks?

463


What is python keyword?

471


Which compiler is best for python?

454


Can you explain how python is interpreted.

437


What is the difference between a tuple and a list?

496






What is use of @classmethod, @staticmethod, @property in python?

441


How are classes created in python?

470


How will you do debugging in python?

477


Does python have a switch-case statement?

476


Tell us something about python iterators.

484


Can python function return multiple values?

440


Which oops talks about data hiding?

439


What tools that helps python development do you know?

477


Why do we use join() function in python?

479


Describe about the libraries of python?

501