You are on page 1of 29

Dr R.

Madana Mohana

FUNCTIONS-2:
Variable Scope and Lifetime
The return statement

https://www.youtube.com/c/RASINENIMADANAMOHANA
Variable Scope and Lifetime

The return statement

OUTLINE Example Programs


VARIABLE SCOPE AND LIFETIME
In Python, we can't just access any variable from
any part of our programs.
Some of the variables may not event exist for the
entire duration of the program.
In which part of the program we can access a
variable and in which parts of the program a
variable exists depends on how the variables
have been declared.
VARIABLE SCOPE AND LIFETIME
Therefore, we need to understand the following two
concepts:
1. Scope of the variable: Part of the program in
which a variable is accessible is called its scope.
2. Lifetime of the variable: Duration for which the
variable exists is called its lifetime.
VARIABLE SCOPE AND LIFETIME
1. Local and Global Variables:
Global variables:
Global variables are those variables which are
defined in the main body of the program file.
They are visible throughout the program file.
VARIABLE SCOPE AND LIFETIME
1. Local and Global Variables:
Local variables:
A variable which is defined within a function is local to
that function.
A local variable can be accessed from the point of its
definition until the end of the function in which it is
defined.
It exists as long as the function executing.
Function parameters behave like local variables in the
function.
VARIABLE SCOPE AND LIFETIME
1. Local and Global Variables:
Local variables:
Moreover, whenever we use the assignment operator
(=) inside a function, a new local variable is created
(provided a variable with the same name is not defined
in the local scope).
Example Program with local and global variables

#Program to understand the difference between local and


global variables
num1 = 20 # global variable
print("Global variable num1 = ",num1)
def func(num2): #num2 is a function parameter
print("In Function - Local Variable num2 = ",num2)
num3 = 30 # num3 is a local variable
print("In Function - Local Variable num3 = ",num3)
func(40) # 40 is passed as an argument i.e. num2 to the
function
print("num1 again = ",num1) # global variable is being accessed
print("num3 outside function = ",num3) # Error-Local variable
can't be used outside the function in which it is defined
Example Program with local and global variables
#Program to understand the difference between local and global
variables
Output:
Global variable num1 = 20
In Function - Local Variable num2 = 40
In Function - Local Variable num3 = 30
num1 again = 20
Traceback (most recent call last):
File "C:/Users/admin/Downloads/CBIT OOPS USING PYTHON w.e.f.
13.06.2022/RMM OOPP LAB PROGRAMS/functions-local-global
varaibles.py", line 10, in <module>
print("num3 outside function = ",num3)# Error-Local variable
can't be used outside the function in which it is defined
NameError: name 'num3' is not defined. Did you mean: 'num1'?
Comparison between Global and Local Variables

Global Variables Local Variables


1. They are defined in the 1. They are defined within a
function and is local to that
main body of the program
function.
file. 2. They can be accessed from the
2. They can be accessed point of its definition until the
throughout the program end of the block in which it is
file. defined.
3. Global variables are 3. They are not related in any way
accessible to all functions in to other variables with the same
names used outside the
the program.
function.
VARIABLE SCOPE AND LIFETIME
2. Using the Global Statement:
To define a variable defined inside a function as global,
we must use the global statement.
This declares the local or the inner variable of the
function to have module scope.
Global Statement - Example Program
Program to demonstrate the use of global statement
var = "Good" # global variable
def show():
global var1
var1 = "Morning"
print("In Function var is:",var)
show()
print("Outside function, var1 is:",var1)# Accessible as
it is global variable
print("Var is:",var)
Global Statement - Example Program

Program to demonstrate the use of global statement


Output:
In Function var is: Good
Outside function, var1 is: Morning
Var is: Good
Global Statement - Example Program
Program to demonstrate name clash of local and global variable
var = "Good" # global variable
def show():
var = "Morning"
print("In Function var is:",var)
show()
print("Outside function, var is:",var)
Output:
In Function var is: Morning
Outside function, var is: Good
Global Statement - Example Program
Program to demonstrate modifying a global variable
var = "Good" # global variable
def show():
global var
var = "Morning"
print("In Function var is:",var)
show()
print("Outside function, var is:",var)
var = "Fantastic"
print("Outside function, after modification, var
is:",var)
Global Statement - Example Program
Program to demonstrate modifying a global variable
Output:
In Function var is: Morning
Outside function, var is: Morning
Outside function, after modification, var is: Fantastic
Global Statement - Example Program
Program to demonstrate access of variables in inner and outer
functions
def outer_func():
outer_var = 20
def inner_func():
inner_var = 30
print("Outer variable = ",outer_var)
print("Inner variable = ",inner_var)
inner_func()
print("Outer variable = ",outer_var)
print("Inner variable = ",inner_var)#Not accessible
outer func() #Function call
Global Statement - Example Program
Program to demonstrate access of variables in inner and outer
functions
Output:
Outer variable = 20
Inner variable = 30
Outer variable = 20
Traceback (most recent call last):
File "C:/Users/admin/Downloads/CBIT OOPS USING PYTHON w.e.f. 13.06.2022/RMM
OOPP LAB PROGRAMS/functions-modifying a global variable.py", line 11, in
<module>
outer_func() #Function call
File "C:/Users/admin/Downloads/CBIT OOPS USING PYTHON w.e.f. 13.06.2022/RMM
OOPP LAB PROGRAMS/functions-modifying a global variable.py", line 10, in
outer_func
print("Inner variable = ",inner_var)#Not accessible
Global Statement - Example Program
Program to demonstrate name clash variables in case of nested functions
def outer_func():
var = 20
def inner_func():
var = 30
print("Inner variable = ",var)
inner_func()
print("Outer variable = ",var)
outer_func() #Function call
OUTPUT:
Inner variable = 30
Outer variable = 20
VARIABLE SCOPE AND LIFETIME
3. Resolution of Names:
Scope defines the visibility of a name within a block.
If a local variable is defined in a block, its scope is that
particular block.
If it is defined in a function, then its scope is all blocks
within that function.
When a variable name is used in a code block, it is
resolved using the nearest enclosing scope.
If no variable of that name is found, then a NameError is
raised.
Global Statement - Resolution of Names

Program that demonstrates using a variable defined in


global namespace
def func():
print(str)
str = "Helo World!" # str is a global string because
it has been defined before calling the function
func()
OUTPUT:
Helo World!
Global Statement - Resolution of Names
Program that demonstrates using a local variable with same
name as that of global
def f():
print(str) #global
str = "Helo World!" #local
print(str)
str = "Welcome to Object Oriented Programming using Python"
f()
OUTPUT:
UnboundLocalError: local variable 'str' referenced before
assignment
Note: We can't define a local variable with the same name as that of global variable.
Global Statement - Resolution of Names
Program that demonstrates using a local variable with same name
as that of global
def f():
global str
print(str)
str = "Helo World!"
print(str)
str = "Welcome to Object Oriented Programming using Python"
f()
OUTPUT:
Welcome to Object Oriented Programming using Python
Helo World!
Note: We can't define a local variable with the same name as that of global
variable. If you want to do that, you must use the global statement.
THE RETURN STATEMENT
The return Statement:
return is a keyword.
return statement is optional statement.
It is used to return one value or more than one values.
The return statement is used to exit a function and go
back to the place from where it was called.
Whenever control reach the return statement of a function
then without executing the remaining part of the function
control will comes out from function execution by
returning some value.
THE RETURN STATEMENT
The return Statement:
The return value of the function can be stored into a
variable and we can use that variable in the remaining part
of the function.
If we are not storing the return value of a function in any
variable then that data will become as a garbage
collection.
We can define 'n' number of return statements in a
function.
THE RETURN STATEMENT
Syntax:
return [ expression_list ]
This statement can contain an expression that gets
evaluated and the value is returned.
If there is no expression in the statement or the return
statement itself is not present inside a function , then
the function will return the None object.

THE retrun STATEMENT


Write a function with no return values
def sample():
print("Helo World!")
return
sample()
sample()
OUTPUT:
Helo World!
Helo World!
THE retrun STATEMENT
Write a function to return only one value
def biggest(x, y):
if x>y:
return x
else:
return y
print("Biggest Number = ",biggest(10, 20))
print("Biggest Number = ",biggest(100, 20))
print("Biggest Number = ",biggest(20, 40))
OUTPUT:
Biggest Number = 20
Biggest Number = 100
Biggest Number = 40
THE retrun STATEMENT
Write a function to return more than one value
def calculate(x,y):
return x+y, x-y, x*y, x/y
a,b,c,d = calculate(10,20)
print("x+y = ",a)
print("x-y = ",b)
print("x*y = ",c)
print("x/y = ",d)
OUTPUT:
x+y = 30
x-y = -10
x*y = 200
x/y = 0.5

You might also like