CHAPTER-5
FUNCTIONS IN PYTHON
5.1 Definition: Functions are the subprograms that perform specific task. Functions are the
small modules.
5.2 Types of Functions:
There are two types of functions in python:
1. Library Functions (Built in functions)
2. Functions defined in modules
3. User Defined Functions
ii
Built in functions
aa Types of functions
Functions defined in
modules
dh
User defined functions
pa
1. Library Functions: These functions are already built in the python library.
2. Functions defined in modules: These functions defined in particular modules. When
you want to use these functions in program, you have to import the corresponding module
of that function.
3. User Defined Functions: The functions those are defined by the user are called user
defined functions.
1. Library Functions in Python:
These functions are already built in the library of python.
For example: type( ), len( ), input( ) etc.
[Link] Page 38
2. Functions defined in modules:
a. Functions of math module:
To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>[Link](49)
7.0
2 ceil( ) Returns the upper integer >>>[Link](81.3)
82
3 floor( ) Returns the lower integer >>>[Link](81.3)
81
4 pow( ) Calculate the power of a number >>>[Link](2,3)
ii
8.0
5 fabs( ) Returns the absolute value of a number >>>[Link](-5.6)
5.6
6
aa exp( ) Returns the e raised to the power i.e. e3
b. Function in random module:
random module has a function randint( ).
>>>[Link](3)
20.085536923187668
dh
randint( ) function generates the random integer values including start and end values.
Syntax: randint(start, end)
It has two parameters. Both parameters must have integer values.
Example:
pa
import random
n=[Link](3,7)
*The value of n will be 3 to 7.
3. USER DEFINED FUNCTIONS:
The syntax to define a function is:
def function-name ( parameters) :
#statement(s)
[Link] Page 39
Where:
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of function header.
One or more valid python statements that make up the function body. Statements must
have same indentation level.
An optional return statement to return a value from the function.
ii
Example:
aa def display(name):
print("Hello " + name + " How are you?")
5.3 Function Parameters:
dh
A functions has two types of parameters:
1. Formal Parameter: Formal parameters are written in the function prototype and function
header of the definition. Formal parameters are local variables which are assigned values from
the arguments when the function is called.
2. Actual Parameter: When a function is called, the values that are passed in the call are
pa
called actual parameters. At the time of the call each actual parameter is assigned to the
corresponding formal parameter in the function definition.
Example :
def ADD(x, y): #Defining a function and x and y are formal parameters
z=x+y
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.
[Link] Page 40
5.4 Calling the function:
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
Syntax:
function-name(parameter)
Example:
ADD(10,20)
ii
OUTPUT:
aa
Sum = 30.0
How function works?
dh
def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)
pa
… .. …
… .. …
The return statement:
The return statement is used to exit a function and go back to the place from where it was
called.
There are two types of functions according to return statement:
a. Function returning some value (non-void function)
b. Function not returning any value (void function)
[Link] Page 41
a. Function returning some value (non-void function) :
Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x
Example-2 Function returning multiple values:
def sum(a,b,c):
ii
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a tuple
aa print(S)
OUTPUT:
(7, 7, 11)
dh
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately
pa
print(s1, s2, s3)
OUTPUT:
7 7 11
b. Function not returning any value (void function) : The function that performs some
operationsbut does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)
[Link] Page 42
OUTPUT:
Hello
None
5.5 Scope and Lifetime of variables:
Scope of a variable is the portion of a program where the variable is recognized. Parameters
and variables defined inside a function is not visible from outside. Hence, they have a local
scope.
There are two types of scope for variables:
ii
1. Local Scope
aa
2. Global Scope
1. Local Scope: Variable used inside the function. It can not be accessed outside the function.
In this scope, The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the
dh
value of a variable from its previous calls.
2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a
variable is the period throughout which the variable exits in the memory.
pa
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT:
Value inside function: 10
Value outside function: 20
[Link] Page 43
Here, we can see that the value of x is 20 initially. Even though the function my_func()changed
the value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the
one outside. Although they have same names, they are two different variables with different
scope.
On the other hand, variables outside of the function are visible from inside. They have a global
scope.
We can read these values from inside the function but cannot change (write) them. In order to
modify the value of variables outside the function, they must be declared as global variables
ii
using the keyword global.
aa
5.6 RECURSION:
Definition: A function calls itself, is called recursion.
5.6.1Python program to find the factorial of a number using recursion:
dh
Program:
def factorial(n):
if n == 1:
return n
else:
pa
return n*factorial(n-1)
num=int(input("enter the number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num = = 0:
print("The factorial of 0 is 1")
else:
print("The factorial of ",num," is ", factorial(num))
[Link] Page 44
OUTPUT:
enter the number: 5
The factorial of 5 is 120
5.6.2 Python program to print the Fibonacci series using recursion:
Program:
def fibonacci(n):
if n<=1:
ii
return n
else:
aa return(fibonacci(n-1)+fibonacci(n-2))
num=int(input("How many terms you want to display: "))
for i in range(num):
dh
print(fibonacci(i)," ", end=" ")
OUTPUT:
How many terms you want to display: 8
pa
0 1 1 2 3 5 8 13
5.6.3 Binary Search using recursion:
Note: The given array or sequence must be sorted to perform binary search.
[Link] Page 45
ii
aa
dh
Program:
def Binary_Search(sequence, item, LB, UB):
pa
if LB>UB:
return -5 # return any negative value
mid=int((LB+UB)/2)
if item==sequence[mid]:
return mid
elif item<sequence[mid]:
UB=mid-1
return Binary_Search(sequence, item, LB, UB)
else:
LB=mid+1
[Link] Page 46
return Binary_Search(sequence, item, LB, UB)
L=eval(input("Enter the elements in sorted order: "))
n=len(L)
element=int(input("Enter the element that you want to search :"))
found=Binary_Search(L,element,0,n-1)
if found>=0:
print(element, "Found at the index : ",found)
ii
else:
print("Element not present in the list")
aa
5.7 lambda Function:
lambda keyword, is used to create anonymous function which doesn’t have any name.
While normal functions are defined using the def keyword, in Python anonymous functions are
dh
defined using the lambda keyword.
Syntax:
lambda arguments: expression
pa
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.
Example:
value = lambda x: x * 4
print(value(6))
Output:
24
[Link] Page 47
In the above program, lambda x: x * 4 is the lambda function. Here x is the argument and x *
4 is the expression that gets evaluated and returned.
Programs related to Functions in Python topic:
1. Write a python program to sum the sequence given below. Take the input n from the
user.
1 1 1 1
1+ + + + ⋯+
1! 2! 3! 𝑛!
Solution:
def fact(x):
j=1
ii
res=1
aa while j<=x:
res=res*j
j=j+1
return res
dh
n=int(input("enter the number : "))
i=1
sum=1
while i<=n:
f=fact(i)
pa
sum=sum+1/f
i+=1
print(sum)
2. Write a program to compute GCD and LCM of two numbers
def gcd(x,y):
while(y):
x, y = y, x % y
return x
[Link] Page 48
def lcm(x, y):
lcm = (x*y)//gcd(x,y)
return lcm
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
ii
print("The G.C.D. of", num1,"and", num2,"is", gcd(num1, num2))
aa
dh
pa
[Link] Page 49