Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Module III

Functions
A function is a block of organized, reusable code that is used to perform
a single, related action. Functions provide better modularity for your
application and a high degree of code reusing.
Advantage of Functions in Python
There are the following advantages of Python functions.
 Using functions, we can avoid rewriting the same logic/code
again and again in a program.
 We can call Python functions multiple times in a program and
anywhere in a program.
 We can track a large Python program easily when it is divided
into multiple functions.
 Reusability is the main achievement of Python functions.
Categories of functions
Two categories of functions are existing in Python.
1.Built-in-functions.
2.User defined functions
Built-in Functions
The python interpreter has several functions that are always present for
use. These functions are known as Built-in Functions. The different
built-in-functions are
1.Mathematical functions
The math module is used to access mathematical functions in the
Python. All methods of this functions are used for integer or real type
objects, not for complex numbers.
To use this module, we should import that module into our code.
import math
Constant of math module
Pi: Return the value of pi: 3.141592
Example
import math
print("Value of PI :",math.pi)
Output
Value of PI : 3.141592653589793
Functions of math module
Numeric functions
math.ceil(x) :Return the Ceiling value. It is the smallest integer, greater
or equal to the number x.
math.fabs(x): Returns the absolute value of x.
math.factorial(x):Returns factorial of x. where x ≥ 0
math.floor(x): Return the Floor value. It is the largest integer, less or
equal to the number x.
math.remainder(x, y): Find remainder after dividing x by y.
Example
import math
x=eval(input("Enter no1 :"))
print("Ceiling value of number ",x," is ",math.ceil(x))
print("Absolute value of number ",-15," is ",math.fabs(-15))
print("Factorial of number ",4," is ",math.factorial(4))
print("Floor value of number ",x," is ",math.floor(x))
print("Remainder of number ",12,"/",5," is ",math.remainder(12,5))
Output
Enter no1 :12.55
Ceiling value of number 12.55 is 13
Absolute value of number -15 is 15.0
Factorial of number 4 is 24
Floor value of number 12.55 is 12
Remainder of number 12 / 5 is 2.0
Power and Logarithmic Functions
math.pow(x, y) :Return the x to the power y value.
math.sqrt(x) : Finds the square root of x
math.log2(x):Returns the Log of x, where base is 2
math.log10(x):Returns the Log of x, where base is 10
Example
import math
x=eval(input("Enter no1 :"))
print("Power of number ",x," with 3 is ",math.pow(x,3))
print("Square root of number ",x," is ",math.sqrt(x))
print("Log value of ", x,"with base 2 is ",math.log2(x))
print("Log value of " ,x,"with base 10 is ",math.log10(x))
Output
Enter no1 :4
Power of number 4 with 3 is 64.0
Square root of number 4 is 2.0
Log value of 4 with base 2 is 2.0
Log value of 4 with base 10 is 0.6020599913279624
Trigonometric functions
math.acos(x) :Return the arc cosine of x, in radians.
math.asin(x) :Return the arc sine of x, in radians.
math.atan(x): Return the arc tangent of x, in radians.
math.cos(x) :Return the cosine of x radians.
math.sin(x): Return the sine of x radians.
math.tan(x) :Return the tangent of x radians.
2.DateTime functions
Module named datetime is used to work with dates.
Functions
Datetime.date.today() : Returns date only. The returned date contains
year, month, and day.
datetime.datetime.now() : Returns date and time. The returned date
contains year, month, day, hour, minute, second, and microsecond.
strftime() Method : The datetime object has a method for formatting date
objects into readable strings. The method is called strftime(), and takes
one parameter, format, to specify the format of the returned string:
Syntax :
time.strftime(format[, t])
t − This is the time in number of seconds to be formatted.
format − This is the directive which would be used to format given time.
The following directives can be embedded in the format string
%a - abbreviated weekday name
%A - full weekday name
%b - abbreviated month name
%B - full month name
%D - same as %m/%d/%y
%e - day of the month (1 to 31)
%m - month (01 to 12)
%M - minute
Example
#datetime module
import datetime
print("Date :",datetime.date.today())
print("Date with time :",datetime.datetime.now())
x=datetime.date.today()
print("Year :",x.year)
print("Month :",x.month)
print("Day :",x.day)
x = datetime.datetime(2020, 5, 17)
print("Given Date :",x)
x = datetime.datetime.now()
print("Monthname of today:",x.strftime("%B"))
print("Monthname :",x.strftime("%b"))
print("Dayname of today:",x.strftime("%A"))
print("Dayname :",x.strftime("%a"))
output
Date : 2020-09-17
Date with time : 2020-09-17 16:13:52.623365
Year : 2020
Month : 9
Day : 17
Given Date : 2020-05-17 00:00:00
Monthname of today: September
Monthname : Sep
Dayname of today: Thursday
Dayname : Thu
Random Numbers in Python
Python defines a set of functions that are used to generate or manipulate
random numbers. This particular type of functions are used in a lot of
games, lotteries or any application requiring random number generation.
To generate integers
random.randrange(start, stop[, step])
Example:
import random
print("Random number :",random.randrange(1, 10,2))
output 1
Random number : 3
output 2
Random number : 5
To generate real numbers
random.random()
Return the next random floating point number in the range [0.0, 1.0).
Example:
import random
print("Random number :",random.random())
output 1
Random number : 0.03131925722763895
output 2
Random number : 0.9029876084846352
To generate random number from a sequence/collection
random.choice(seq):
Example:
import random
l1=[10,20,30,40,50]
print("Random number from list :",random.choice(l1))
print("Random number from list :",random.choice(l1))
l2=(5,15,25,35,45)
print("Random number from Tuple :",random.choice(l2))
print("Random number from Tuple:",random.choice(l2))
output
Random number from list : 40
Random number from list : 30
Random number from Tuple : 35
Random number from Tuple: 45
User defined functions
In Python, a function is a group of related statements that performs a
specific task. Functions help break our program into smaller and
modular chunks. As our program grows larger and larger, functions
make it more organized and manageable. It also avoids repetition and
makes the code reusable. User defined functions need
1.Function definition
Function definition is used specify name of the function, arguments and
block of statements that will execute when the function is called.
Syntax
def function_name(parameters):
"""docstring"""
statement(s)
return(expression)
1. Keyword def that marks the start of the function header. The first line of
the function is known as header and the rest of the function is known as
body of the function. The header line must end with a colon.
2. A function name to uniquely identify the function. Function naming
follows the same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function.
They are optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function
does.
6. One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Example 1 – Program using python IDLE
def disp():
"""Simple funtion"""
print("Welcome to user defined function")
print("Ok")
Example 1 – Program using python Interactive mode(>>>)
When we type a function definition in interactive mode(command line),
the ellipses(…)are automatically displayed by the interpreter in the next
line to tell us that the definition is not complete. User can enter
statements using indentation. In order to end the function definition we
need to enter an empty line.

2.Calling a function
Once we have defined a function, we can call it from another function,
program or even from the Python prompt. To call a function we simply
type the function name with appropriate parameters. User can call a
function multiple times.
Syntax:
<functionname()>
Example
disp()
disp()
Program for displaying a message using a function
def disp():
"""Simple funtion"""
print("Welcome to user defined function")
print("Ok")
disp() #function calling
disp() #function calling
output
Welcome to user defined function
Ok
Welcome to user defined function
Ok
Docstrings
The first string after the function header is called the docstring and is
short for documentation string. It is briefly used to explain what a
function does. Although optional, documentation is a good programming
practice. We generally use triple quotes so that docstring can extend up
to multiple lines. This string is available to us as the __doc__ attribute
of the function.
Example
def disp():
"""Simple function"""
print("Welcome to user defined function")
print("Ok")
disp()
disp()
print("Documentaion string :",disp.__doc__)
output
Welcome to user defined function
Ok
Welcome to user defined function
Ok
Documentaion string : Simple function
Function variables
When we define a function, Python interpreter also creates a variable
with the same name.
Example
def disp():
"""Simple function"""
print("Welcome to user defined function")
print("Ok")
print ("Function variable :",disp)
print("Type of disp is :",type(disp))
output
Function variable : <function disp at 0x02D1B858>
Type of disp is : <class 'function'>
Nested function calling
Python allows to invoke one function from another function.
Example
#nesting of function
def disp():
print ("Welcome")
print("dear ",end="")
show()
print("ok ")
def show():
print("students")
print("Nesting of functions")
disp()
output
Nesting of functions
Welcome
dear students
ok
Parameters and Arguments
Parameters and arguments are the values or expression passed to the
functions between parentheses. Arguments are variables/values passed
with functions at the time of function calling. The value of the
arguments are always assigned to variables and these variables are
known as parameters. Parameters are included at the time of function
definition within function header.
Formal Arguments
Formal arguments are arguments passed at the time of function calling.
They are
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required arguments/Positional arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call
should match exactly with the function definition.
Example
#Function using required arguments
def total(n1,n2,n3):
res=n1+n2+n3
print("Number 1",n1)
print("Number 2",n1)
print("Number 3",n1)
print("Sum is",res);
print("Function using required arguments")
a=eval(input("Enter no "))
b=eval(input("Enter no "))
c=eval(input("Enter no "))
total(a,b,c)
output
Function using required arguments
Enter no 10
Enter no 20
Enter no 30
Number 1 10
Number 2 10
Number 3 10
Sum is 60
2.Keyword arguments
Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the arguments
by the parameter name. This type of argument can also be skipped or
can also be out of order.
Example 1
def disp(n1,n2,n3):
res=n1+n2+n3
print("Number 1 :",n1)
print("Number 2 :",n2)
print("Number 3 :",n3)
print("Sum is",res);
print("Function using keyword arguments")
disp(n1=10,n3=30,n2=20)
output
Function using keyword arguments
Number 1 : 10
Number 2 : 20
Number 3 : 30
Sum is 60
Example 2
#Function using keyword arguments
#Function using keyword arguments
def disp(n1,n2,n3):
res=n1+n2+n3
print("Number 1 :",n1)
print("Number 2 :",n2)
print("Number 3 :",n3)
print("Sum is",res);
print("Function using keyword arguments")
disp(n1=10,n2=20,n3=30)
output
Function using keyword arguments
Number 1 : 10
Number 2 : 20
Number 3 : 30
Sum is 60
3.Default arguments
In default arguments, we can assign value to a parameter at the time of
function definition. The value is considered as default value of the
parameter. If we do not provide a value to the parameter at the time of
calling, it will pick the default value.
#Function using default arguments
def disp(n1=10,n2=20,n3=30):
res=n1+n2+n3
print("Number 1 :",n1)
print("Number 2 :",n2)
print("Number 3 :",n3)
print("Sum is",res);
print("Function using default arguments")
disp();
disp(15);
disp(15,25)
disp(15,25,40)
Function using default arguments
Number 1 : 10
Number 2 : 20
Number 3 : 30
Sum is 60
Number 1 : 15
Number 2 : 20
Number 3 : 30
Sum is 65
Number 1 : 15
Number 2 : 25
Number 3 : 30
Sum is 70
Number 1 : 15
Number 2 : 25
Number 3 : 40
Sum is 80
4.Variable-length Arguments
Python function allows to receive multiple arguments in a single
parameter in function definition. These arguments are called variable-
length arguments.
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
The special syntax * var_args_tuple in function definition in python is
used to pass a variable number of arguments to a function. It is used to
pass a non-keyworded, variable-length argument list. The syntax is to
use the symbol * to take in a variable number of argument. The variable
that we associate with the * becomes an iterable.
Example
#Function using variable-length arguments
def disp(*args):
print("Items in collection - Tuple :",args); #displaysitems from
arguments
for arg in args:
print("Item : ",arg)
print("Type of args :",type(args))
print("Function using variable-length arguments")
disp(15);
disp(15,25)
disp(15,25,40)
disp()
output
Function using variable-length arguments
Items in collection - Tuple : (15,)
Item : 15
Type of args : <class 'tuple'>
Items in collection - Tuple : (15, 25)
Item : 15
Item : 25
Type of args : <class 'tuple'>
Items in collection - Tuple : (15, 25, 40)
Item : 15
Item : 25
Item : 40
Type of args : <class 'tuple'>
Items in collection - Tuple : ()
Type of args : <class 'tuple'>
The return statement
The return statement is used to exit a function and go back to the place
from where it was called.
Syntax
Return(<variable>/<expression>)
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.
Example
#Function returning values
def total(a,b,c):
res=a+b+c
return(res)
a=total(15,25,35)
print("Total :",a)
output
Total : 75
If arguments are not supplied
a=total()
TypeError: total() missing 3 required positional arguments: 'a', 'b', and 'c'
Returning multiple values from a function
Python allows to return multiple values from a function. While returning
values from a function returned values are stored with tuple object.
Example
#Function returning values
def total(a,b,c):
res=a+b+c
return(res,res/3)
a=total(10,20,30)
print("Type of a :",type(a))
print("Total :",a)
Output
Type of a : <class 'tuple'>
Total : (60, 20.0)
Inner functions/Nested functions
A function which is defined inside another function is known as inner
function or nested function. Nested functions are able to access variables
of the enclosing scope. Inner functions are protected from everything
happening outside the function. This process is also known
as Encapsulation.
Example1
def outer():
print("Welcome to outer function")
def inner():
print("Welcome to inner function")
inner()
outer()
output
Welcome to outer function
Welcome to inner function
Example2
def outer():
print("Welcome to outer function")
def inner():
print("Welcome to inner function")
inner()
outer()
inner()
output
Welcome to outer function
Welcome to inner function
Traceback (most recent call last):
File "C://Python37-32/f8.py", line 7, in <module>
inner()
NameError: name 'inner' is not defined
Python Anonymous/Lambda Function
In Python, an anonymous function is a function that is defined without a
name.While normal functions are defined using the def keyword in
Python, anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.
Syntax
lambda arguments: expression
Lambda functions can have any number of arguments but only one
expression. The expression is evaluated and returned. Lambda functions
can be used wherever function objects are required. We use lambda
functions when we require a nameless function for a short period of
time.
Example
square= lambda x: x *x
print(square(5))
output
25
Lambda x:x*x is the lambda function. Here x is the argument and x*x is
the expression that gets evaluated and returned. This function has no
name. It returns a function object which is assigned to the identifier
square. We can call it as a normal function. The statement square=
lambda x: x *x is same as
def square(x):
return(x*x)
Example 2
total= lambda a,b,c:a+b+c
a=eval(input("Enter no :"))
b=eval(input("Enter no :"))
c=eval(input("Enter no :"))
print("Sum :",total(a,b,c))
print("Sum :",total(10,20,30))
output
Enter no :5
Enter no :8
Enter no :10
Sum : 23
Sum : 60
Recursion
Recursion is the process of function to call itself. Every recursive
function must have a base condition that stops the recursion or else the
function calls itself infinitely. The Python interpreter limits the depths of
recursion to help avoid infinite recursions, resulting in stack overflows.
By default, the maximum depth of recursion is 1000. If the limit is
crossed, it results in RecursionError.
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using
recursion.
3. Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
3. Recursive functions are hard to debug.
Example
Recursive function to find the factorial of an integer. Factorial of a
number is the product of all the integers from 1 to that number. factorial
of 6 (denoted as 6!) is 1*2*3*4*5 = 120.
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = eval(input("Enter number :"))
x=factorial(num)
print("The factorial of", num, "is", x))
output 1
Enter number :1
The factorial of 1 is 1
output 2
Enter number :3
The factorial of 3 is 6
In the above example, factorial() is a recursive function as it calls itself.
When we call this function with a positive integer, it will recursively call
itself by decreasing the number. Each function multiplies the number
with the factorial of the number below it until it is equal to one. This
recursive call can be explained in the following steps.
factorial(3) # 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call
Our recursion ends when the number reduces to 1. This is called the base
condition.
Function Composition
Function composition is the way of combining two or more functions in
such a way that the output of one function becomes the input of the
second function and so on. For example, let there be two functions “F”
and “G” and their composition can be represented as F(G(x)) where “x”
is the argument and output of G(x) function will become the input of F()
function.
Example
def square(x):
return(x*x)
def sdigit(x):
s=0
num=x
print(x)
while(x>0):
d=x%10
s=s+d
x=x//10
print("Sum of digits of ",num, " is ",s);
n=eval(input("Enter numnber :"))
sdigit(square(n))
output
Enter numnber :4
16
Sum of digits of 16 is 7
Global and Local variables
global Variables : In Python, a variable declared outside of the function
or in global scope is known as a global variable. A global variable can
be accessed inside or outside of the function.
Example 1
#global variable
total=100
def exam():
print ("Total inside function = :",total);
print("End of function")
print("Total outside function = :",total);
exam()
output
Total outside function = : 100
Total inside function = : 100
End of function
Global keyword in Python
Global keyword is a keyword that allows a user to modify a variable
outside of the current scope. Global keyword is used inside a function
only when we want to do assignments or when we want to change a
variable. Global is not needed for printing and accessing. There is no
need to use global keyword outside a function.
Example
#global keyword
total=500
def exam():
global total;
print ("Total variable inside function = :",total);
total=total+5;
print ("Total variable inside function = :",total);
print("End of function")
exam()
print ("Total variable outside function = :",total);
output
Total variable inside function = : 500
Total variable inside function = : 505
End of function
Total variable outside function = : 505
Local Variables
A variable declared inside the function's body or in the local scope is
known as a local variable.
Example
#local variable
def exam():
total=100
print ("Total variable inside function = :",total);
print("End of function")
exam()
print ("Total variable outside function = :",total);
Output
Total variable inside function = : 100
End of function
Traceback (most recent call last):
File "C:/Python37-32/f9.py", line 7, in <module>
print ("Total variable outside function = :",total);
NameError: name 'total' is not defined
Global variable and Local variable with same name
Python allows to include global and local variable with same name
within a program. Local variable have high precedence than global
variables within a function.
Example
#global and local variable with same name
total=500
def exam():
total=100
print ("Total variable inside function = :",total);
print("End of function")
exam()
print ("Total variable outside function = :",total);
output
Total variable inside function = : 100
End of function
Total variable outside function = : 500

Difference between local and global variable


Parameter Local Global
It is declared outside
Scope It is declared inside a function.
the function.
If it is not initialized, a garbage If it is not initialized
Value
value is stored zero is stored as default.
It is created before the
It is created when the function program’s global
Lifetime starts execution and lost when execution starts and lost
the functions terminate. when the program
terminates.
It is stored on a fixed
It is stored on the stack unless
Memory storage location decided by the
specified.
compiler.

Important questions
1. Define function.
2. Write a short note on mathematical functions, datetime functions and
random numbers.
3. Define user defined function and write a short note on components of
a function.
4. Define Parameter and argument.
5. Explain about different types of arguments used with functions.
6. Write a short note on return statement.
7. Define recursion. Write an example of recursion.
8. What is meant by lambda expression ?
9. Define Function composition.
10. Differentiate between global and local variable.

You might also like