Python Programming
UNIT: III
Defining, Redefining, and Calling Functions * Variable Scope
and Lifetime * return statement * Required, Keyword,
Default, and Variable Arguments * Lambda and Recursive
Functions * Documentation Strings, Modules, and Packages *
Standard Library, globals(), Locals(), and reload().
Introduction: A function is a block of code that performs a well
defined task. Python enables its programmers to break up a program
into functions, each of which can be written more or less
independently of the others. The code of one function is completely
insulated from the codes of the other functions.
In the above diagram func1() is called to perform a well defined task.
When func1() is called , the control of execution is passed to the first
statement in the function. All the statements in the function are
executed and then the control of execution is passed to the next
statement after the function call.
Advantages of using functions:
1. It facilitates top-down modular programming.
2. Using functions we can easily write, read, modify and debug a
lengthy program.
3. The length of a program can be reduced by using functions at
appropriate places.
Function Definition : A function definition consists of two parts. They
are
1. Function header(first line of the function)
2. Function body
The general form of a function is
def function-name(parameter list):
statement 1
statement 2
return val
Krishnaveni Degree College :: Narasaraopet Page No. : 1
Python Programming
UNIT: III
1. The function header consists of function-name along with the
parameters that are to be passed to the called function.
2. The body of the function consists of set of statements to perform
a well defined task and the last statement is the return statement
which returns the res to the calling function.
Ex:
def sumtwo(a, b):
sum=a+b
return sum
Variable Scope And Lifetime: Scope refers to the visibility of
variables and Lifetime of variable refer to the duration for which the
variable exists.
Local Variables: Local Variables are variable that are declared inside
method or block. Local variables are assessable only within the
declared method or block and cannot assessable outside that
method or block.
Example:
def func1():
x='Local_x'
print(x)
func1() # calling func1()
Output :-
Local_x
Example:
def func1():
x='Local_x'
print(x)
func1()
print(x) # Accessing Local Variable ‘x’ Outside func1() method
Output :-
Local_x
NameError: name 'x' is not defined
Example
def func1(x):
print(x)
func1('hello')
Output :-
Hello
Note: This variable are local to its method and can not assessed out
that method.
Krishnaveni Degree College :: Narasaraopet Page No. : 2
Python Programming
UNIT: III
Global Variables: A variable which is defined in the main body
(outside all of the functions or blocks) of a file is called a global
variable. They are available through out the life time of a program.
They can be accessed from any part of the program.
Example:
x = 'Global_x'
def func1():
print(x) # Calling variable ‘x’ inside func1()
func1()
print(x) # Calling variable ‘x’ outside func1()
Output :-
Global_x
Global_x
Example:
x='Global_x'
def func1():
x='Local_x'
print(x)
func1()
print(x)
Output :-
Local_x
Global_x
Example:
x='Global_x'
def func1():
global x
x='Local_x'
print(x)
func1()
print(x)
Output :-
Local_x
Local_x
Types of arguments in python functions: An argument or a
parameter is a variable which contains data that is sent to the
function as input. The arguments are basically divided into two
types. They are
Krishnaveni Degree College :: Narasaraopet Page No. : 3
Python Programming
UNIT: III
1. Formal Arguments
2. Actual Arguments
Formal arguments: The arguments that are used in the function
definition are called formal arguments.
Actual arguments: The arguments that are used in the function call
are called actual arguments.
Ex:
def sum(a, b):
c=a+b # a and b are formal arguments
print(c)
# call the function
x = 10
y = 15
sum(x, y) # x and y are actual arguments
Output:
25
In python, depending on the way the arguments are sent to the
function, the arguments can be classified into four types:
1. Positional arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
5. keyword variable-length argument
Positional Arguments in Python: If there are three arguments (formal
arguments) in the function definition, then three actual arguments
are sent while calling the function. The actual arguments will be
received by the formal arguments in the same order as in the
function call.
Example:
def sum(x, y):
res=x+y
return res
#calling function
a=float([nput(“Enter any number: “))
b=float([nput(“Enter any number: “))
s=sum(a,b)
print(“Sum=”,s)
Keyword Arguments in Python: In the function call, if we send the
values using keys then they are called keyword arguments.
Example:
def sum(x, y):
print("x=",x)
print("y=",y)
Krishnaveni Degree College :: Narasaraopet Page No. : 4
Python Programming
UNIT: III
res=x+y
return res
#calling function
a=float(input("Enter any number: "))
b=float(input("Enter any number: "))
s=sum(y=a,x=b)
print("Sum=",s)
Note: We can use both positional and keyword arguments
simultaneously. But first, we must take positional arguments and
then keyword arguments, otherwise, we will get syntax errors.
#Program to demo positional arguments and then keyword
arguments
def sum(x, y,z):
print("x=",x)
print("y=",y)
print("z=",z)
res=x+y
return res
#calling function
a=float(input("Enter any number: "))
b=float(input("Enter any number: "))
c=float(input("Enter any number: "))
s=sum(a,z=b,y=c)
print("Sum=",s)
Default Arguments: In the function definition, while declaring
parameters, we can assign some value to the parameters, which are
called default values. Such default values will be considered when
the function call does not send any data to the parameter.
Example:
#Program to demo default arguments
def sum(x, y,z=0):
print("x=",x)
print("y=",y)
print("z=",z)
res=x+y+z
return res
#calling function
a=float(input("Enter any number: "))
b=float(input("Enter any number: "))
c=float(input("Enter any number: "))
s=sum(a,b)
print("Sum=",s)
s=sum(a,b,c)
Krishnaveni Degree College :: Narasaraopet Page No. : 5
Python Programming
UNIT: III
print("Sum=",s)
Variable Length Arguments: Sometimes, the programmer does not
know how many values need to pass to function. In that case, the
programmer cannot decide how many arguments to be given in the
function definition. Therefore, we use variable-length arguments to
accept n number of arguments. The variable-length argument is an
argument that can accept any number of values. The variable-length
argument is written with a ‘*’ (one star) before the variable in the
function definition.
Example:
#Program to demo Variable Length arguments
def sum(*x):
res=0
for num in x:
res=res+num
return res
#calling function
a=float(input("Enter any number: "))
b=float(input("Enter any number: "))
c=float(input("Enter any number: "))
d=float(input("Enter any number: "))
s=sum(a)
print("Sum=",s)
s=sum(a,b)
print("Sum=",s)
s=sum(a,b,c)
print("Sum=",s)
s=sum(a,b,c,d)
print("Sum=",s)
Keyword variable Length arguments: Python uses **kwargs to pass
the variable length of keyword arguments to the function. In the
function, we use the double asterisk ** before the parameter name
to denote this type of argument. The arguments are passed as a
dictionary and these arguments make a dictionary inside function
with name same as the parameter excluding double asterisk **.
#Program to demo Keyword variable Length arguments
def sum(**submrk):
res=0
for subn, mrk in submrk.items():
print("%s = %s"%(subn, mrk))
res=res+mrk
return res
#calling function
Krishnaveni Degree College :: Narasaraopet Page No. : 6
Python Programming
UNIT: III
s=sum(eng=90,tel=80,maths=100)
print("Total=",s)
Recursive Function: A function is called recursive when it is called
by itself.
Example:
# Factorial with recursive function in python
def factorial(n):
if n ==0:
result=1
else:
result = n * factorial(n-1)
return result
x= factorial(4)
print("Factorial of 4 is: ",x)
Output:
Factorial of 4 is: 24
Example:
# Factorial without recursive function in python
def f1(n):
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of “,n,” is ", fact)
f1(4)
Output:
Factorial of 4 is 24
Lambda Function (Anonymous Functions): The name of the
function is the mandatory item in the function definition. But, in
python, we have a keyword called ‘lambda’ with which we can define
a simple function in a single line without actually naming it. Such
functions are called lambda functions.
Syntax: lambda argument_list: expression
Example:
#Lambda Function in Python
s = lambda a: a*a
x=s(4)
Krishnaveni Degree College :: Narasaraopet Page No. : 7
Python Programming
UNIT: III
print(x)
Output:
16
Example:
#Lambda Function in Python
add = lambda a,b: a+b
x=add(4,5)
print(x)
Output:
9
Points to Remember while working with Python Lambda
Functions:
1. A lambda function can take any number of arguments but
should have only one expression.
2. It takes the parameters and does some operation on them and
returns the result, just the same as normal functions.
3. The biggest advantage of lambda functions is that a very
concise code can be written which improves the readability of
the code.
4. This can be used for only simple functions but not for complex
functions.
Docstrings: Python documentation strings (or docstrings) provide a
convenient way of associating documentation with Python modules,
functions, classes, and methods.
The doc string line should begin with a capital letter and end
with a period.
The first line should be a short description.
If there are more lines in the documentation string, the second line
should be blank, visually separating the summary from the rest of
the description.
The following lines should be one or more paragraphs describing the
object’s calling conventions, its side effects, etc.
Declaring Docstrings: The docstrings are declared using ”’triple
single quotes”’ or “””triple double quotes””” just below the class,
method or function declaration.
Accessing Docstrings: The docstrings can be accessed using the
__doc__ method of the object or using the help function.
Example 1:
#Docstring using triple single quotes
Krishnaveni Degree College :: Narasaraopet Page No. : 8
Python Programming
UNIT: III
def my_function():
'''Demonstrates triple double quotes
docstrings and does nothing really.'''
return
print("Using __doc__:")
print(my_function.__doc__)
print("Using help:")
help(my_function)
Output:
Using __doc__:
Demonstrates triple double quotes
docstrings and does nothing really.
Using help:
Help on function my_function in module __main__:
my_function()
Demonstrates triple double quotes
docstrings and does nothing really.
Example 2:
# Docstrings using triple double quotes
def my_function():
"""Demonstrates triple double quotes
docstrings and does nothing really."""
return None
print("Using __doc__:")
print(my_function.__doc__)
print("Using help:")
help(my_function)
Output:
Using __doc__:
Demonstrates triple double quotes
docstrings and does nothing really.
Using help:
Help on function my_function in module __main__:
Krishnaveni Degree College :: Narasaraopet Page No. : 9
Python Programming
UNIT: III
my_function()
Demonstrates triple double quotes
docstrings and does nothing really.
Modules: Module is a file with a .py extension that has definitions of
functions and variables which can be used by many programs. The
basic way to use a module is to add import module_name as the first
line of the program. Use module_name.varname or
module_name.funcname to access variables or functions in that
module.
#Python file with sum definition with name as sumfile.py
def sum(x, y):
res=x+y
return res
#Python Program which uses sum definition form another file
import sumfile
#calling function
a=float(input(“Enter any number: “))
b=float(input(“Enter any number: “))
s=sumfile.sum(a,b)
print(“Sum=”,s)
The from..import statement: A module may contain many variables
or functions. When you import a module , all the functions will be
imported. When a specific function is to be imported then use from
mod_name import func_name.
#Python file with sum definitionwith name as sumsubfile.py
def sum(x, y):
res=x+y
return res
def sub(x, y):
res=x-y
return res
#Python Program which uses sum definition form another file
From sumsubfile import sum
#calling function
a=float(input(“Enter any number: “))
b=float(input(“Enter any number: “))
s=sum(a,b)
print(“Sum=”,s)
Advantages of Modules: Modules provide many benefits in the
software design. They are
Krishnaveni Degree College :: Narasaraopet Page No. : 10
Python Programming
UNIT: III
1. Modules can be reused in many programs
2. They are easy to understand and use.
3. A module can import another module.
4. It is customary but not mandatory to place all import
statements at the beginning of the module.
5. A module will be imported once irrespective of numbers of
times it is used.
Packages: A package is a hierarchical file directory structure that
has modules and another packages within it. Every package in
Python is a directory which must have a special file called __init__.py.
This file may not have even have a single line of code. It is simply
added to the directory to indicate that it is a package.
#Python file with sum definition with name as sumfile.py stored in
MyPack
def sum(x, y):
res=x+y
return res
#Python program to add two numbers using functions in MyPack
from MyPack import sumfile
a=int(input("Enter first number:"))
b=int(input("Enter first number:"))
Krishnaveni Degree College :: Narasaraopet Page No. : 11
Python Programming
UNIT: III
s=sumfile.sum(a,b)
print("Sum of",a,"and",b,"is",s)
Standard Library: Python support three types of modules. They
are
1. Modules written by the programmer
2. Modules that are installed by external sources.
3. Modules that are pre-installed with python.
Modules that are pre-installed with python are known as standard
library modules. Some useful standard library modules are string,
syss, datetime, math, random etc. Some of these modules are
written in python and others are written in C.
#Python program to add two numbers using command line
argumnets
import sys
a=int(sys.argv[1])
b=int(sys.argv[2])
s=a+b
print("Sum of",a,"and",b,"is",s)
Globals(), , Locals(), and reload(): The globals() and locals()
functions are used to return the nams in the global and local name
spaces. If locals() is called from within a function, names that can be
accessed locally from that function will be returned. If globals() is
called from within a function, names that can be accessed globally
from that function will be returned. When a module is imported into
a program, the code will be executed only once. If ww wand to
reexecute the code, then reload() function is used.
Example:
#Python Program which demos locals() and globals()
x=10
def sum():
global x
y=10
print(locals())
print(globals())
res=x+y
return res
s=sum()
print("Sum=",s)
Krishnaveni Degree College :: Narasaraopet Page No. : 12
Python Programming
UNIT: III
Example:
#Python program to demo reload functions
import sumfile
import importlib
a=int(input("Enter first number:"))
b=int(input("Enter first number:"))
s=sumfile.sum(a,b)
print("Sum of",a,"and",b,"is",s)
a1=int(input("Enter first number:"))
b1=int(input("Enter first number:"))
importlib.reload(sumfile.sum)
s1=sumfile.sum(a1,b1)
print("Sum of",a1,"and",b1,"is",s1)
Krishnaveni Degree College :: Narasaraopet Page No. : 13