Chapter-7 Functions
Chapter-7 Functions
Chapter – 7
Functions
Introduction –
You might have experienced bigger occasions in homes or in schools and colleges. For example,
college annual day is one of the bigger occasions for that academic year. For smooth and easy
conducting of entire programme, head of institution will form a different committee, discipline
committee etc. as sub tasks. We also find repetition of tasks such as greeting guest -1, greeting guest
-2 etc. These kind of repetitive tasks are handled easily and quickly by the committee which is
formed for that purpose. Therefore, conducting of entire program will be easier and systematic.
A function is a block of statements that performs the specific task. Basically, this concept of
function is used while performing larger tasks (program that contain more number of lines of codes),
because complexities are more in such program and difficult to manage.
An idea is to put some repeatedly or frequently used tasks together and makes a subprogram /
functions so that instead of writing the same code again and again for different inputs, we can call a
function to reuse code present in the function.
#Program to calculate the payable amount for the tent without using function.
print ("Enter values for the cylindrical part of the tent in meters\n")
h = float (input ("Enter height of the cylindrical part:"))
r = float (input ("Enter radius:"))
l = float (input ("Enter the slant height of the conical part in meters:"))
csa_conical = 3.14 * r * l
csa_cylindrical = 2 * 3.14 * r
canvas_area = csa_conical + csa_cylindrical
#Program to calculate the payable amount for the tent using UDF.
def cyl(h,r):
area_cyl = 2 * 3.14 * r * h
return (area_cyl)
def con(l,r):
area_con = 3.14 * r * l
return(area_con)
Page1
Functions I PUC - CS
def post_tax_price(cost):
tax = 0.18 * cost
net_price = cost + tax
return(net_price)
Definition of Function – “A function is a block of statements that performs the specific task.”
OR
Types of Functions –
1. Library Function / Built – in function
2. User Defined Function
1. Library Function –
It is a built – in function. These types of functions are predefined in the programming
language. The definitions are stored in the library of that language. The group of functions of
certain type can be accessed by importing corresponding modules.
Advantages of Functions –
Code Reusability:Write once, use multiple times.
Improved Readability: Makes the main program flow easier to follow.
Easier Debugging: Problems can be isolated within a specific function.
Modularity: Divides complex tasks into smaller, manageable pieces.
Scalability: Easy to extend and maintain.
Page2
Functions I PUC - CS
Creating User Defined Function –
The items enclosed in “[ ]” are called parameters and they are optional. Hence, a function
may or may not have parameters. Also, a function may or may not return a value.
Function header always ends with a colon (:).
Function name should be unique. Rules for naming identifiers also apply for function naming.
The statements outside the function indentation are not considered as part of the function.
Program – Write a user defined function to add 2 numbers and display their sum.
def addnum():
fnum = int(input("Enter first number:"))
snum = int(input("Enter second number:"))
sum = fnum + snum
print("The sum of ", fnum, "and", snum,"is", sum)
addnum()
Output:
Argument is a value passed to the function when it‟s called. Whereas parameter is a
variable defined in a function‟s definition.
Key differences –
Parameters Arguments
Defined in the function header Provided during the function call
Acts as a variable to receive input The actual value passed into the
function
Page3
Functions I PUC - CS
Program – Write a program using a user defined function that displays sum of first n
natural numbers, where n is passed as an argument.
Output:
Program – Write a program using user defined function that accepts an integer and
increments the value by 5. Also display the id of argument (before function call), id of
parameter before increment and after increment.
def incrValue(num):
print("Parameter num has value:", num,"\n id = ", id(num))
num = num + 5
print("num incremented by 5 is ", num," \n Now id is", id(num))
number = int(input("Enter a number:"))
print("id of argument number is:", id(number))
incrValue(number)
Output:
Page4
Functions I PUC - CS
Program –Write a program using user defined function myMean() to calculate the
mean of floating values stored in a list.
def myMean(myList):
total = 0
count = 0
for i in myList:
total = total + i
count = count + 1
mean = total /count
print("The calculated mean is :", mean)
myList = [1.3, 2.4, 3.5, 6.9]
myMean(myList)
Output:
Program –Write a program using a user defined function calcFact() to calculate and
display the factorial of a number num passed as argument.
def calcFact(num):
fact = 1
for i in range(num,0, -1):
fact = fact * i
print("Factorial of ", num,"is", fact)
num = int(input("Enter the number:"))
calcFact(num)
Output:
Page5
Functions I PUC - CS
Program – Write a program using a user defined function that accepts the first name
and last name as arguments, concatenate them to get full name and displays the output
as:
def fullname(first,last):
fullname = first + " " + last
print("Hello", fullname)
first = input("Enter first name:")
last = input("Enter last name:")
fullname(first,last)
Output:
Default Parameter – In Python, you can define default parameter values in a function. These
default values are used when no argument is provided for the corresponding parameter during the
function call.
Page6
Functions I PUC - CS
Output:
Program – Write a program using user defined function calcPow() that accepts base
and exponent as arguments and returns the base exponent where base and exponent are
integers.
def calcpow(number,power):
result = 1
for i in range(1,power+1):
result = result * number
return result
base = int(input("Enter the value for the Base:"))
expo = int(input("Enter the value for the exponent:"))
answer = calcpow(base,expo)
print(base,"raised to the power", expo,"is", answer)
Output:
Page7
Functions I PUC - CS
Types of UDF in Python:
1. Function with no argument and no return value.
2. Function with no argument and with return value.
3. Function with argument(s) and no return value.
4. Function with argument(s) and return value(s).
Flow of Execution –
Flow of execution can be defined as the order in which the statement in a program is executed. The
python interpreter starts executing the instructions in a program from the first statement. The
statements are executed one by one, in the order of appearance from top to bottom. This process you
can understand with the following steps.
Define a function with or without parameter(s) specifications as per the requirements of the
program.
Call a function with or without argument(s), whenever need comes. But function must be
defined before its call in the program.
Generally, statements present in the main program are executed sequentially, as function call
encounters, control shifts to a function and passes arguments (if available) which is present in
the function call to corresponding parameters.
All the statements present in the function which is invoked are executed and returns a control
to calling function with or without the return value(s).
As control enters to a calling function, continues the execution of statements present after the
function call statement.
Page8
Functions I PUC - CS
Consider the following programming example.
display()
def display():
print("Welcome to Python")
Output:
The error „display is not defined‟ is produced even though the function has been defined. When a
function call is encountered, the control has to jump to the function definition and execute it. In the
above program, since the function call precedes the function definition, the interpreter does not find
the function definition and hence an error is raised.
From the above example, it is understood that, function must be defined before calling a function as
shown in the following example.
[7] print(Area)
[8] print(“Thanks”)
Page9
Functions I PUC - CS
Program – Write a program using user defined function that accepts length
and breadth of a rectangle and returns the area and perimeter of the
rectangle.
def calcAreaPeri(length,breadth):
area = length * breadth
perimeter = 2 * (length + breadth)
return (area,perimeter)
l = float(input("Enter length of the rectangle:"))
b = float(input("Enter breadth of the rectangle:"))
area, perimeter = calcAreaPeri(l,b)
print("Area is:", area, "\n Perimeter is:", perimeter)
Output:
Program – Write a program that simulates a traffic light. The program should consist of the
following.
1. A user defined function trafficLight( ) that accepts input from the user, displays an error
message if the user enters anything other than RED, YELLOW, and GREEN. Function light( )
is called and following is displayed depending upon return value from light( ).
2. A user defined function light( ) that accepts a string as input and returns 0 when the input
is RED, 1 when the input is YELLOW and 2 when the input is GREEN. The input should be
passed as an argument.
3. Display “ SPEED THRILLS BUT KILLS” after the function trafficLight( ) is executed.
def trafficLight():
signal = input("Enter the colour of the traffic light:")
if (signal not in ("RED", "YELLOW", "GREEN")):
print("Please enter a valid Traffic light colour in CAPITALS")
else:
value = light(signal)
if (value == 0):
print("STOP, Your Life is Precious.")
Page10
Functions I PUC - CS
elif (value == 1):
print("PLEASE GO SLOW.")
else:
print("GO!, Thank you for being patient.")
def light (colour):
if (colour == "RED"):
return (0)
elif (colour == "YELLOW"):
return (1)
else:
return (2)
trafficLight( )
print("SPEED THRILLS BUT KILLS")
Output:
Scope of a Variable:
A variable defined inside a function cannot be accessed outside it. Every variable has a well –
defined accessibility. The part of the program where a variable is accessible can be defined as the
scope of that variable. A variable can have one of the following two scopes:
A variable that has global scope is known as a global variable and a variable that has a local scope is
known as a local variable.
Types of Variables:
1. Local variable
2. Global variable
1. Local Variable – A variable that is defined inside any function or block is known as a local
variable. It can be accessed only inside the function or block where it is defined. It means that has
limited scope.
2. Global Variable – A variable that is defined outside any function or block is known as a global
variable. It can be accessed in any function or block after its definition. Any change made to the
global variable will impact all the functions in the program where that variable can be accessed.
num = 5
def myFunc1():
y = num + 5
Page11
Functions I PUC - CS
print("Accessing num -> (global) in myFunc1, value = ", num)
print("Accessing y -> (local variable of myFunc1) accessible, value=",y)
myFunc1()
print("Accessing num outside myFunc1", num)
print("Accessing y outside myFunc1", y)
Output:
num = 5
def myFunc1():
global num
print("Accessing num = ", num)
num = 10
print("num reassigned =", num)
myFunc1()
print("Accessing num outside myFunc1", num)
Output:
Note: When local variable name is same as global variable name, then it is considered local
variable to that function and hides the global variable.
Num = 10
def testfun():
Num = 20
print("Value of num=", Num)
testfun()
Output:
Page12
Functions I PUC - CS
Function
Types of Functions:
1. Standard Library function
2. User Defined Function
1. Standard Library Function – There are two standard library functions – built in functions and
modules.
Built – in Functions: In python, built – in functions that are always readily available for use. These
functions are part of the Python interpreter and serve various purposes.
a = int(input(“Enter a number:”))
b=a*a
print (“The square of ”, a , “is”, b)
In the above program input( ), int( ) and print( ) are the built – in functions. The set of instructions to
be executed for these built – in functions are already defined in the python interpreter.
Built – in Functions:
Page13
Functions I PUC - CS
Data Type Conversion Functions
bool( ) – converts given value into Boolean type.
Mathematical Functions
abs( ) – returns an absolute value of a number.
Other functions
_imports_ ( ) – import modules dynamically.
Page14
Functions I PUC - CS
Commonly used built – in functions:
>>> abs(-25.23)
25.23
Divmod(x, y) Returns quotient and remainder. >>> divmod(17,5)
(3,2)
(x and y are integers)
>>>divmod(-7,2)
(-4, 1)
max(x,y,z) Returns largest number. >>> max([1, 2, 3, 4])
(x, y, z are integers/ float) 4
>>>min(“Sincerity”)
„S‟
ie based on ASCII value.
pow(x,y) x raised to the power y. >>> pow(2,5)
(x and y are integer or 32.0
floation numbers).
>>> pow(5.2,2.2)
39.2
sum(x[,num]) Finds sum of all the elements in >>> sum([2, 4, 7, 3])
(x is a numeric sequence and the sequence from left to right. 16
num is an optional argument.)
>>> sum([1,2,3],4)
10
len (x) Counts elements in x. >>> len(“Welcome”
7
(x is sequence or a
dictionary.) >>> len([12, 34, 98])
3
Page15
Functions I PUC - CS
Module –
In programming, we may need group of functions in many programs. In such case, instead of
copying these functions in different programs, we can keep all of them in single file called module
and use them in different programs. In simple, a module is a group of functions.
In python, a module is a file containing python definitions and statements. It‟s a way of organizing
and reusing of codes.
A module is a .py file containing executable code as well as function definitions.
You can import a module into other modules using the import statement. Once we import a
module, we can directly use all the functions of that module.
importing of modules gives access to all the functions in the module. To call a function of a module,
the function name should be preceded with the name of the module with a dot(.) as a separator.
Syntax : modulename.functionname( )
1. math module – It contains all possible mathematical functions which are very commonly used in
our program. Module must be imported before the use of any of the functions of respective module.
In order to use the math module we need to import it using the following statement:
import math
Page16
Functions I PUC - CS
math.factorial(x) Factorial of x >>> math.factorial(5)
x is a positive integer 120
math.fmod(x,y) Returns x % y with sign of x >>> math.fmod(4,4.9)
4.0
(x and y are integer / float)
>>> math.fmod(-4.9,2.5)
-2.4
math.gcd(x,y) Returns the greatest common >>> math.gcd(10,2)
divisor of two integers 2
x and y are positive integer
math.pow(x,y) x raised to the power y (xy) >>> math.pow(3,2)
9.0
x and y are interger / float
>>> math.pow(4,2.5)
32.0
math.sqrt(x) square root of x. >>> math.sqrt(144)
12
x may be a positive integer or
floating point number >>> math.sqrt(.64)
0.8
math.sin(x) sine of x in radians >>> math.sin(0)
0
x may be an integer or
floating point number in >>> math.sin(6)
radians -0.279
2. random module – This module contains functions that are used for generating random
numbers. Some of the commonly used functions in random module are given in below table. For
using this module, we can import it using the following statement:
import random
Page17
Functions I PUC - CS
3. Statistics Module – This module provides functions for calculating statistics of numeric (Real –
valued) data. Some of the commonly used functions in statistics module are given in table.
import statistics
>>>statistics.mode([“red”, “blue”,
“blue”, “black”])
blue
From statement – If you import a particular module, all the functions of that module will be
loaded into memory. But you may or may not need all those functions. Therefore most of the
functions are loaded into memory, even though they are not useful. These type of situations can be
avoided by using “from” statement in python.
“from” statement is used to fetch only required functions from a particular module. It loads only
specified function from that module. Thus its reduces memory
Example 1–
Output:
0.9796352504608387
Example 2–
Output:
25.0
Page18