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
Can python replace bash?
What are the two main types of functions in python?
What are python methods?
Do you know what is numpy and how is it better than a list in python?
What are uses of lambda?
What does __ file __ mean?
What happens if an error occurs that is not handled in the except block?
How to access sessions in flask?
How to check whether a module is installed in python?
List of lists changes reflected across sublists unexpectedly?
Explain important characteristics of python objects?
What is a class method?
What will be the output of ['!!welcome!!']*2?
How do you get the current working directory using python?
How will you change case for all letters in string in python?