Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

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

How many hours learn python?

783


How to create a unicode string in python?

880


What is the starting point of python code execution?

958


How to find whether string is alphanumeric or not?

818


How do I sleep in python?

759


Tell us something about garbage collector in python?

866


What is timestamp in python?

861


How to count the occurrences of a list item?

817


What does quit () do in python?

756


What is the method does join() in python belong?

884


What is map () in python?

780


What are the implementation in python program?

857


What is the use of metaclass in python?

826


What animal sleeps the most?

785


what is the statement that can be used in python if the program requires no action but requires a statement syntactically?

761