You are on page 1of 8

Programming using Python

prutor.ai Amey Karkare


Dept. of CSE
IIT Kanpur

For any queries reach out to rahulgr@iitk.ac.in or rahulgarg@robustresults.com


or whatsapp 9910043510

1
Python Programming
Scope Rules

prutor.ai
Scope of a Name
• Functions allow us to divide a program
into smaller parts

prutor.ai
– each part does a well defined task
• Scope of a name is the part of the
program in which the name can be used

3
Nov-16 Programming, Functions
Scope of a Name
• Two variables can have the same name only if
they are declared in separate scopes.

prutor.ai
• A variable can not be used outside its scope.
• In a Python program, scope of a name can be
determined by looking at the code
– static scoping or lexical scoping

4
Nov-16 Programming, Functions
Scope Rules: Functions
def max(a,
max(a1,b)b1):
:
• The scope of the variables if (a
(a1>>b):
b1):

m1, a1, b1
present in the argument list m1==aa1
m

scope of
of a function's definition is else:

prutor.ai
the body of that function. m1==bb1
m
return m m1
• If a variable is assigned
within a function, its scope def min(a,
min(a2,b)b2):
:
is the body of the function. if (a
(a2<<b):
b2):

m2, a2, b2
m2==aa2
m
• A name is added to the
scope of
else:
scope associated with a m2==bb2
m
function only under the return m m2
We can reuse the names
above two cases. as scopes are different
5
Nov-16 Programming, Functions
Scope Search
• Suppose a name x is referenced in the body of a
function f
• If x is not found in the body of f, then it is searched in

prutor.ai
the stack frame of the function g whose definition
encloses the definition of f.
• If not found in g , then x is searched in the stack frame
of the function h whose definition encloses the
definition of g
• This continues until x is found or all enclosing
functions are exhausted. If x is not found, error is
produced.
6
Nov-16 Programming, Functions
Globals
• Globals allow functions to communicate with
each other indirectly

prutor.ai
– Without parameter passing/return value
• Convenient when two seemingly “far-apart”
functions want to share data
– No direct caller/callee relation
• If a function has to update a global, it must re-
declare the global variable with global
keyword.
7
Nov-16 Programming, Functions
Globals
PI = 3.14
>>> print(area (100))
def perimeter(r):
31400.0
return 2 * PI * r
>>> print(perimeter(10))
def area(r):
62.800000000000004

prutor.ai
return PI * r * r
>>> update_pi()
def update_pi():
>>> print(area(100))
global PI
31415.999999999996
PI = 3.14159
>>> print(perimeter(10))
62.832
defines PI to be of float type with value 3.14. PI
can be used across functions. Any change to PI
in update_pi will be visible to all due to the use
8
of global.
Nov-16 Programming, Functions

You might also like