adspace


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 do I list all files of a directory?

937


What is the best notepad?

891


How do you check if a list is empty in python?

955


How do you write if else in python?

1046


Explain the inheritance in python with an example?

985


Tell me what are different methods to copy an object in python?

1023


How would you display a file’s contents in reversed order?

937


What is the length of your largest python code? Can you please describe the project?

1133


How to read a 10gb (or larger) file size in python?

893


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

873


How do I download a file over http using python?

926


Is there a way to remove the last object from a list?

1007


What is the process to get the home directory using ‘~' in python?

1015


list some of the data science libraries in python

947


What is the use of assertions in python?

1176