KEMBAR78
Chapter-7 Functions | PDF | Parameter (Computer Programming) | Software Development
0% found this document useful (0 votes)
12 views18 pages

Chapter-7 Functions

The document provides an overview of functions in programming, explaining their definition, types, and advantages. It includes examples of user-defined functions (UDFs) and built-in functions, along with programming exercises demonstrating their usage. Additionally, it covers concepts such as parameters, arguments, return values, and the flow of execution in function calls.

Uploaded by

daviddiop512
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views18 pages

Chapter-7 Functions

The document provides an overview of functions in programming, explaining their definition, types, and advantages. It includes examples of user-defined functions (UDFs) and built-in functions, along with programming exercises demonstrating their usage. Additionally, it covers concepts such as parameters, arguments, return values, and the flow of execution in function calls.

Uploaded by

daviddiop512
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Functions I PUC - CS

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

print ("The area of the canvas is", canvas_area, "m^s2")

unit_price = float (input ("Enter the cost of 1 m^2 canvas:"))


total_cost = unit_price * canvas_area
print ("The total cost of canvas = ",total_cost)

tax = 0.18 * total_cost


net_price = total_cost + tax
print ("Net amount payable = ", net_price)

#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)

print("Enter values of cylindrical part of the tent in meters:")


h = float(input("Height:"))
r = float(input("Radius:"))
csa_cyl = cyl(h,r)
l = float(input("Enter slant height of the conical area in meters:"))
csa_con = con(l,r)

canvas_area = csa_cyl + csa_con


print("Area of canvas =", canvas_area," m^2")

unit_price = float(input("Enter cost of 1 m^2 canvas in rupees:"))


total_cost = unit_price * canvas_area
print("Total cost of canvas before tax = ",total_cost)
print("Net amount payable(including tax) =",post_tax_price(total_cost))

Definition of Function – “A function is a block of statements that performs the specific task.”

OR

“A function is a sub – program designed for specific purpose”.

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.

2. User Defined Function –


It‟s a type of function which is defined by the user within a program according to the user /
program requirement.

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 –

Syntax: def function_name( [parameter1, parameter2,………parameter N ] ):


statement / s
[return <value>]

 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:

Arguments and Parameters –

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.

def sumSquares(n): #n is the parameter


sum = 0
for i in range(1, n+1):
sum = sum + i
print("The sum of first",n,"natural number is:", sum)
num = int(input("Enter the value for n:")) #num is a argument
sumSquares(num) #function call

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:

String as Parameters – In Python, a string can be passed as a parameter to a function, allowing


the function to use or modify the string. Strings are immutable in Python, so any changes made to
the string within the function will not affect the original string unless explicitly returned or
manipulated outside the function.

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.

Program – Write a program that accepts numerator and denominator of a factorial


number and calls a user defined function mixedFraction() when the fraction formed is
not a proper function. The default value of denominator is 1. The function displays a
mixed fraction only if the fraction formed by the parameters does not evaluate to a
whole number.

def mixedFraction(num, deno = 1):


remainder = num % deno
if remainder!= 0:
quotient = int(num/deno)
print("The mixed fraction=", quotient,"(",remainder, "/",deno,")")
else:
print("The given fraction evaluates to a whole number")
num = int(input("Enter the numerator:"))
deno = int(input("Enter the denominator:"))
print("You entered:",num,"/",deno)
if num > deno:
mixedFraction(num,deno)
else:
print("It is a proper fraction")

Page6
Functions I PUC - CS
Output:

Function returning value –


Generally, a function will return a value when it is called. But in some situations, a function
may not return a value to a calling function. A function which is not returning value when
it is invoked is called Void function. But in some situations, we may need to return a value
without changing the result. It can be done using return statement.

The reason for using return statement is –


 Returns the control to the calling function.
 Return value(s) or None.

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).

1. Function with no argument and no return value –


A function calls another function with no argument (s). The control switches to a
called function and executes all the statements present in it. Finally control come to a
calling function without any return value(s).

2. Function with no argument and with return value –


A function calls another function with no argument(s). The control switches immediately to a
called function and executes all the statements associates with that function. Finally control
come to a calling function with return value(s).

3. Function with argument(s) and no return value –


A function calls another function with set of argument(s). The control switches to a called
function and argument values are passed on to corresponding parameters. All the statements
present in that function are executed and control come to a calling function without any return
value(s).

4. Function with argument(s) and return value(s) –


It‟s a type of UDF and used in most of the situations. In this, a function calls another function
with set of arguments. The control immediately switches to a called function and argument
values are passed on to corresponding parameters. All the statements present in that function
are executed and control come to a calling function with 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.

#Program to illustrate the flow of execution of functions.

display()
def display():
print("Welcome to Python")

Output:

On executing above program segment, following error is generated.

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.

Order of execution #Program to display some text

[2] def display( ): #function definition

[3] print(“Welcome to Python”)

[1] display( ) #function call statement

Order of execution #Program to calculate area of rectangle.

[4] def RectangleArea(l,b): #function header


[5] return l * b
[1] l = input(“Length:”)
[2] b = input(“Breadth:”)
[3][6] Area = RectangleArea(l,b) #function call

[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( ).

a) “STOP”, your life is precious” if the value returned by light( ) is 0.


b) “Please WAIT, till the light is Green “ if the value returned by light( ) is 1.
c) “GO! Thank you for being patient” if the value returned by light( ) is 2.

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.

Program – Program to access any variable outside the function.

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:

Program – Program to access any variable outside the function.

#Program to access any variable outside the function.

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

Python Standard Library –


Python provides numerous standard library functions and also provision to create customized
user defined functions.

Function

Standard Library User Defined

Built – in Functions Modules

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.

Consider the one Python program:


#A program to calculate square of a number.

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:

Input or Output Functions


input( ) – prompts for user input

output( ) – displays data on screen

Page13
Functions I PUC - CS
Data Type Conversion Functions
bool( ) – converts given value into Boolean type.

chr( ) – returns a character for given ASCII value.

dict( ) – create a dictionary.

float( ) – converts given integer into floating point


number.
int( ) – converts floating numbers into an integer.

list( ) – creates a new list.

ord( ) – returns ASCII value for a given character.

set( ) – create an empty set.

str( ) – converts given input data into string.

tuple( ) – create a new tuple.

Mathematical Functions
abs( ) – returns an absolute value of a number.

divmod( ) – returns quotient and remainder.

max( ) – returns maximum value from the given range.

min( ) – returns minimum value from the given range.

pow(x, y) – returns xy.

sum( ) – returns sum of all numbers of the given range.

Other functions
_imports_ ( ) – import modules dynamically.

len( ) – counts the elements of given sequence.

range( ) – create a list with range ( start and end) values.

type( ) – to know the data type of the variable.

Page14
Functions I PUC - CS
Commonly used built – in functions:

Function Description Example


abs( x ) Absolute value of x with >>> abs (5)
(x may be integer / float) positive sign. 5

>>> 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

>>> max([1.5, 5.72, 3.45])


5.72

>>> max (“Sincerity”)


„y‟
ie based on ASCII value
min(x,y,z) Returns smallest number. >>> min([1,2,3,4])
(x, y, z are integers / float) 1

>>> min([1.9, 2.7,9.5,1.2])


1.2

>>>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.

Syntax of import statement:

import modulename1 [, modulename2,……]

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( )

Built –in modules:


Python library has many built-in modules. The most commonly used modules are:
1. math
2. random
3. statistics

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

Function Description Example


math.ceil(x) Rounds a number up to the >>> math.ceil(-5.7)
nearest integer 5
(x is an integer / float)
>>> math.ceil(5.7)
6
math.floor( ) Rounds a number down to the >>> math.floor(-4.5)
nearest integer -5
x may be an integer or
floating point number >>>math.floor(4.5)
4
math.fabs(x) Returns the absolute value of a >>> math.fabs(6.7)
number, removing any negative 6.7
x may be an integer or sign.
floating point number >>>math.fabs(-6.7)
6.7

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

Function Description Example


random.random( ) Random real number(float) in >>> random.random( )
the range 0.0 to 1.0 0.65333522
random.radiant(x,y) Returns a random number >>> random.randiant(3,7)
between the given range 4
x, y are integer such that x
<=y >>> random.randiant(-3,5)
1
random.randrange(y) Returns random integer >>> random.randrange(5)
between 0 and y 4
random.randrange(x,y) Returns random integer >>> random.randrange(2,7)
between x and y 2

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

Function Description Example


statistics.mean(x) Calculates the mean (average) >>>
of the given data statistics.mean([11,24,32,45,51])
32.6
statistics.median(x) Calculates the median (middle >>>
value) of the given data statistics.median([10,20,30,40,50])
30
statistics.mode(x) mode (the most repeated >>>
value) statistics.mode([11,24,15,18,15])
15

>>>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

Syntax: from modulename import functionName [, functionName,…….]

Example 1–

>>> from random import random


>>> random( )

Output:
0.9796352504608387

Example 2–

>>> from math import ceil, sqrt


>>> value = ceil (624.7)
>>> sqrt(value)

Output:
25.0

Page18

You might also like