0% found this document useful (0 votes)
15 views31 pages

Final Copy Functions Chapter 7

Uploaded by

rokum9432
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)
15 views31 pages

Final Copy Functions Chapter 7

Uploaded by

rokum9432
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/ 31

Chapter-7 : Functions 1|Page

Chapter 7: Functions
Topic to be covered in User Defined Topic to be covered in Standard Library
Function(UDF) Function
1. Syntax with example of UDF 1. Types of standard library function
2. Function header a) Built in function
3. Argument and parameter b) Module(collection of function)
4. Function call 2. Built in function
5. return statement 3. Types of built in function
6. default parameter 4. Built in math function(5 mark)
7. string as parameter 5. Module
8. flow of execution 6. import statement
9. scope of variable 7. Types of module
 global variable a) Math module
 local variable b) Random module
10. Programs using UDF c) Statistic module
11. Types of user defined function 8. from statement
9. Create user defined module
10. Define Docstrings
1. Introduction to Function
 In programming, the use of function is one of the means to achieve modularity and
reusability.
 Function can be defined as a named group of instructions that accomplish a specific
task when it is invoked.
 Once defined, a function can be called repeatedly from different places of the
program without writing all the codes of that function every time, or it can be called
from inside another function, by simply writing the name of the function and passing
the required parameters.
 The programmer can define as many functions as desired while writing the code

Q)Explain the advantages of Function .


Following are the advantages of using functions in a program:
1. Increases readability by using functions, as the program is better organised and easy to
understand.
2. Reduces code length as same code is not required to be written at multiple places in a
program. This also makes debugging easier.
3. Increases reusability, and avoid repetitions of writing the same piece of code.
4. Work can be easily divided among team members and completed in parallel.

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 2|Page

Following are one mark question


1.What is function?
Function can be defined as a named group of instructions(statement) that accomplish a
specific task when it is invoked or called by its name.
2. Why to use function?
In programming, functions are used to achieve modularity and reusability.
3. What is modularity?
The process of dividing program(decomposition) into sub problem or separate independent
blocks of code known as modularity.

 Functions are used to achieve modularity.


4.What is code reusability?
Once function is defined , it can be called repeatedly from different places of the program
without writing all the codes of that function every time.This process is called code
reusability.
5. Mention the types of function
There are two types of functions in python
A) User defined function
B) Standard library function
1. Built-in function
2. Module
6. What is user defined function?
Programmers can write their own functions known as user defined functions.
Or A function which is created by user is called user defined function.
5. What is built-in function?
Built-in functions are the ready-made functions in Python that are frequently used in
programs.

 The Python standard library is an extensive collection of functions and modules that
help the programmer in the faster development of programs.
Note :The Python interpreter has a number of functions built into it. These are the
functions that are frequently used in a Python program. Such functions are known as
built-in functions.

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 3|Page

6. What is module?
A module is a Python file that contains definitions of multiple functions.

 Module is a collection of functions


7. How to bring module to the programs?
• A module can be imported in a program using import statement.Irrespective of the
number of times a module is imported, it is loaded only once.
8. Which statement is used to bring particular functions in a program?
To import specific functions in a program from a module, from statement can be used.
9. What is function call?
Function call is statement which passes arguments and transfer control to called function

 An argument is a value passed to the function during function call which is received
in a parameter defined in function header.
 Python allows assigning a default value to the parameter.
10. What is return statement?
A function returns values to the calling function using return statement.
• Multiple values in Python are returned through a Tuple.
11. What is flow of execution?
Flow of execution can be defined as the order in which the statements in a program are
executed.
12. What is the scope of the variable?
The part of the program where a variable is accessible is defined as the scope of the
variable.
13. What is global variable?
A variable that is defined outside any particular function or block is known as a global
variable.

 It can be accessed anywhere in the program.


14. What is local variable?
A variable that is defined inside any function or block is known as a local variable.

 It can be accessed only in the function or block where it is defined.


 It exists only till the function executes or remains active.

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 4|Page

A)User Defined Function(UDF)


Q) What is user defined function?
Programmers can write their own functions known as user defined functions.
Or A function which is created by user is called user defined function.

1.Q) Explain user defined function with syntax and programming examples
 A function definition begins with def (short for define),followed by function name along
with list of parameters separated by comma.
 The first line of function is called function header
 Function header always ends with a colon (:)
 Function body contain set of executable statements.
 The return statement is the last statement in the function
Syntax for creating User Defined Function
def functionName(parameter1,parameter2,-------,parameterN): Function header

statement 1
statement 2
Function body(set of
----------------
executable instruction
---------------- or statement)

statement N
return (value)
Program to Create User Defined Function(UDF) to calculate sum of three number(function
with argument with return value)
Flow of
execution Program

[5] def calculatesum(x , y , z): #function header

[6] return (x+y+z)


#end of function

[1] a=int(input("Enter first number:"))

[2] b=int(input("Enter second number:"))

[3] c=int(input("Enter third number:"))

[4][7] result=calculatesum(a,b,c) #function call by passing argument value

[8] print("The sum of three number=",result)

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 5|Page

 A function may or may not have parameters


 A function may or may not return a value.
 Function name should be unique. Rules for naming identifiers also applies for function
naming.
Example 1:(function with argument and return value)

def calculatesum (x , y , z): def calculatesum (x , y , z):

return (x+y+z) sum = x+y+z


return sum

Example 2:(function with argument and with no return value)

def calculatesum(x , y , z):


sum=x+y+z
print("The sum of three number=",sum)

Example 3:(function with no argument and no return value)

def calculatesum():
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
sum=a+b+c
print("The sum of three number=",sum)

Example 4:(function with no argument and return value)

def calculatesum():
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
sum=a+b+c
return sum

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 6|Page

3.) Function header


 Function header is a declaration of function.
 It begins with def keyword.
 Function header specifies the function name along with list of parameter followd by
colon:
Syntax of function header
def functionName(parameter1,parameter2,-------,parameterN):
Example of function header
def calculatesum (x , y , z):

3.)Argument and Parameters


An argument is a value passed to the called function during the function call which is
received by the parameters defined in the function heading.

Arguments Parameters
 Arguments are listed in a function call 
Parameters are listed in a function
header
 Arguments values are passed to the  Parameter receives the value of the
called function while function call Argument
 Function call  Function header
result=calculatesum(a,b,c) def calculatesum(x , y , z):

 a, b , c variables are called arguments  x ,y ,z variables are called parameters

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 7|Page

Note:

 Id of two variable x and y are


same because initially they
stored same value.
 Later the x value increment by
20
 So id of x changed but id of y
was not changed.

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.

Description (When argument an parameter refer to same value)


 When function call is made ,the id of parameter and argument will be same Since
parameters receives the value of arguments.
 We can use id() function to find the identity of object (argument and parameter).
 In below program argument n and parameter num are referring to the same value, they
are bound to have the same identity.
 So both refer to same id(identity) or share same memory location.
 But when parameter values are incremented in called function, the id of parameter will
be changed but argument id will not be changed.

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 8|Page

4.)What is function call?Explain with programming example.


 Function call is a statement which transfer the program control to a called
function along with argument values .
 A function can be called or invoked by function call .

Syntax of function call:


Variable = functionName(argument1,argument2,……)
Example
result=calculatesum(a,b,c)

Programming example for function call

output
60
600
150
750
25.8

5.)What is return statement?Explain with programming example.


 The return statement returns the values from the function to the calling function.
 The return statement does the following:
1. Returns the control to the calling function or point of call in the program.
2. return single value or multiple values or return None.
 A function may or may not return a value when called.

syntax Example
return variable return sum
return expression return a+b+c
return values return 25
return v1,v2,v3……….. return p , q , r
return 10 , 20 , 30
def calculateum (x , y , z): def calculatesum (x , y , z):
return (x+y+z) sum=x+y+z
return sum

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 9|Page

Q)What is void function?


 The function which do not return any value. Such functions are called void
functions.
Note:
But a situation may arise, wherein we need to send value(s) from the function to its
calling function.

 This is done using return statement.

Programming example return statement


Program to create user defined function to return area and perimeter of a rectangle using
return statement.
Order of Function returning multiple values
execution
Transfer
[ 4] def calculateAreaPeri(l,b): #function header
control back
to the point [ 5] area=l*b
of call with
return values [6 ] perimeter=2*(l+b)
[7] return area , perimeter
[1 ] length=float(input("Enter the length of the rectangle:"))
[ 2] breadth=float(input("Enter the breadth of the rectangle"))
[ 3][8] a , p =calculateAreaPeri(length,breadth) #function call
Control transfer
[ 9] print("The area of a rectangle=" a) to called function
[10] print("The perimeter of a rectangle=",p) along with values

6.What is default Parameter ? Write a program using default parameter


Default parameter means default value is assigned to parameter when function call
does not have its corresponding argument .
 In below program x, y and z are default parameters which is assigned default value of
100, 200 and 300.
 So, Python allows
assigning a default
value to the
parameter.

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 10 | P a g e

def add( x=100, y=200, z=300):


sum=x+y+z
print("The total=",sum)
#function end here output
add() #function call 1 The total= 600
add(400) #function call 2 The total= 900
add(500,800) #function call 3 The total= 1600
add(10,20,30) #function call 4 The total= 60

Program to join two string without using function


 The + operator is used to concatenate string.
 Concatenation is the process of joining string.

[1] program output


[2] str1=input("Enter first string:") Enter first string:exam
[3] str2=input("Enter second string:") Enter second string:time
[4] str3=str1+str2 The concatenated string is examtime
[5] print("The concatenated string is ",str3)

7. String as Parameters
 User may need to pass string values as an argument, as shown in below program.
Program to join two string using user define function where string used as a
parameter

#function to display full name output


[4] def joinString(first , last): Enter first name: Rahul
[5] fullname=first+" "+last Enter last name: Das
[6] print("Hello",fullname) Hello Rahul Das
#function ends here
[1] str1=input("Enter first name:")
[2] str2=input("Enter last name")
[3] joinString(str1,str2) #function call

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 11 | P a g e

8. Flow of Execution (Order of Execution)


Q)What is flow of execution? Explain with programming example.
Flow of execution can be defined as the order in which the statements in a program are
executed.

 When the interpreter encounters a function definition, the statements inside the
function are not executed until the function is called.
 Later, when the interpreter encounters a function call, there is a little deviation in the
flow of execution.
 The control jumps to the called function and executes the statement of that function.
 After that, the control comes back the point of function call so that the remaining
statements in the program can be executed.

Program to define user defined functions return area and perimeter of a


rectangle

Order of
execution
[ 4] def calculateArea(l , b ): #function header
[ 5] return l*b
[8 ] def calculatePerimeter(l , b): #function header
[9 ] return 2*(l+b)
[1 ] x= float(input("Enter the length of the rectangle:"))
[ 2] y = float(input("Enter the breadth of the rectangle"))
[ 3][6] area = calculateArea(x , y) #function call
[ 7][10] perimeter=calculatePerimeter(x,y) #function call
[11 ] print("The area of a rectangle=",area)
[ 12] print("The perimeter of a rectangle=",perimeter)

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 12 | P a g e

Program to find the area and perimeter of a rectangle without using


function(flow of execution top to down)

flow of
Output
execution
Enter the length:20
[1] l=float(input("Enter the length:"))
Enter the breadth:40
[2] b=float(input("Enter the breadth:"))
The area of the
[3] area=l*b
rectangle= 800.0
[4] perimeter=2*(l+b)
The perimeter of a
[5] print("The area of the rectangle=",area) rectangle 120.

[6] print("The perimeter of a rectangle=",perimeter)

Note:

 Therefore, when we read a program, we should not simply read from top to bottom.
Instead, we should follow the flow of control or execution.
 The function must be defined before its call within a program.
 Flow of execution is also called as order of execution.
Note:
1. The Python interpreter starts executing the instructions in a program from the first
statement.
2. The statements are executed one by one, in the order of appearance from top to
bottom.
1. Program to create four user defined function to perform arithmetic
operation and make function call in the program.

Output

Enter first number:25

Enter second number:10

35

15

250

2.5

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 13 | P a g e

2. Program to create four user defined function to perform arithmetic


Operation and return values to program.

output

3. function with no argument and no return value Hi I PUC student


Exam time
program
Wake up
def show(): #function header
**********
print("Hi I puc student")
Hi I PUC student
print("Exam time")
Exam time
print("Wake up")
Wake up
print(“**********”)
**********
#function end here
Hi I PUC student
show() #function call
Exam time
show() #function call
Wake up
show() #function call
Program:function with no argument and no
program without using output return value
function [2] def helloPython(): #function header
Hi I PUC student
[1]print("Hi I PUC student") [3] print("I love python programming")
Exam time
[2]print("Exam time") [1]helloPython() #function call
Wake up
[3]print("Wake up") Output
**********
[4]print(“**********”) I love python programming

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 14 | P a g e

Flow of
execution Write Function with argument with no return value

[2] def greetings(name): #function header output


[3] print("hello "+name) hello Rahul
[1] greetings("Rahul") #function call Thanks
[4] print("Thanks")

9.)Scope of a variable
Q)What is scope of a variable?
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.
 A variable defined inside a function cannot be accessed outside it.
 Every variable has a well-defined accessibility.

Q)Compare global variable and local variable.Write a program using local


and global variable.
Local variable Global variable
 A variable that is defined inside of  A variable that is defined
any function or a block is known as outside of any of function or any
a local variable. block is known as a global
variable.
 Local variable only accessible within a  Global variable accessible
function where it is defined. throughout the program and by
all the functions defined.

 It exists only till the function  Any change made to the global
executes. So change in local variable will impact all the
variable will not impact all the functions in the program.
function in the program.
 Local variable created while entering  Global variable active and alive
the function and local variable throughout the program.
destroyed when it exit the function.

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 15 | P a g e

Program to show the uses of local Program to show the uses of global
variable variable

def function1(): m=100 #global variable


x=20 # local variable def function1():
print(x) print(m) #access global variable
def function2(): def function2():
y=50 #local variable print(m) #access global variable
print(y) def function3():
def function3(): print(m) #access global variable
z=100 #local variable function1()
print(z) function2()
function1() # function call function3()
function2() # function call print(m) #access global variable
function3() # function call

print(x) #accessing local variable

print(y) #accessing local variable

print(z) #accessing local variable

Output for local variable program Output for global variable program
20 100
50 100
100 100
Traceback (most recent call last): 100
File "D:/python programs/local.py", line
13, in <module>

print(x)

NameError: name 'x' is not defined

Note :Any modification to global variable is


permanent and affects all the functions where
it is used.

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 16 | P a g e

Q) What happen when the global and local variable name is same?
When local variable name is same name as the global variable name then it is considered
local variable to that function and hides the global variable.
Program

num=10 #global variable Output


def test():
local variable hide global
num=40 #local variable variable

print("local variable hide global variable") Value of num= 40

print("Value of num=",num)
test() #function call

Note: In above program both local and global variable having same name as num

Q) Why to use global keyword?


If the modified value of a global variable is to be used within function, then the keyword
global should be prefixed to the variable name in the function.

m=100 #global variable

def function1(): Output


print(m) #access global variable 100
def function2(): 100
print(m) #access global variable 500
def function3(): 500
global m

m=m+400 #modify global variable

print(m) #access global variable

function1() #function call

function2() #function call

function3() #function call

print(m) #access global variable

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 17 | P a g e

10.)Python programs using user defined function(UDF)


2.)What is nested function? Give
1. )Program to create four user
programming example
defined functions and make
function call in the program When a function is called within another
function directly or indirectly then it is
program called as nested function.
def function1(): Output program Output
print("Regular") Regular #nested function CEBA
def function2(): JEE def function1(): KCET
print("JEE") KCET function2() JEE
def function3(): CEBA print("Regular") Regular
print("KCET") def function2():
def function4(): function3()
print("CEBA") print("JEE")
function1() #function call def function3():
function2() #function call function4()
function3() #function call print("KCET")
function4() #function call def function4():
print("CEBA")
function1() #function call

3.)program to find sum and average of three number using user defined function

def displaySumAverage(): #function header Output


a=int(input("Enter first number:")) Enter first number:100
b=int(input("Enter second number:")) Enter second number:200
c=int(input("Enter third number:")) Enter third number:300
sum=a+b+c
The sum of three number= 600
average=sum/3
The average of three number 200.0
print("The sum of three number=",sum)

print("The average of three number=",average)

displaySumAverage() #function call

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 18 | P a g e

4)Write a program that simulates a traffic light . It is required to make 2 user


defined functions trafficLight() and light().
Note: You make function call to trafficLight() from main program then the
traffiLight() function will make call to light() (nested function call)

Output 1:

Enter the colour of the traffic light: yellow

PLEASE GO SLOW.

SPEED THRILLS BUT KILLS

Output 3: Output 2:

Enter the colour of the traffic light: red Enter the colour of the traffic light: green

STOP, Your Life is Precious. GO!,Thank you for being patient.

SPEED THRILLS BUT KILLSSPEED THRILLS BUT SPEED THRILLS BUT KILLS
KILLS
Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science
Chapter-7 : Functions 19 | P a g e

5.Write a program to find the sum and average of three number using global
variable.
Note: In below program

 a , b , c are global variables


 sum and avg are local variables
Order of
execution
[ 1] a=int(input("Enter first number:"))
Output
[ 2] b=int(input("Enter second number:"))
Enter first number:100
[3] c=int(input("Enter third number:"))
Enter second number:200
[5] def total():
Enter third number:300
[6 ] sum=a+b+c
The sum of three number= 600
[ 7] print("The sum of three number=" , sum)
The average of three number 200.0
[ 10] def average():

[ 11] avg=(a+b+c)/3

[12] print("The average of three number ", avg)

[4][8] total() #function call

[9][13] average() #function call

6.program to find area and circumference of a circle using function

[3] def circleArea(r):


Output:
[4] return 3.14*r*r
Enter the radius of a circle:4
[6] def circleCircum(r):
Area of a circle= 50.24
[7] return 2*3.14*r
circumference of a circle= 25.12
[1] radius = int(input("Enter the radius of a circle:"))
[2] area = circleArea(radius) #function call

[5] circum = circleCircum(radius) #function call


[8] print("Area of a circle=",area)

[9] print("circumference of a circle=",circum)

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 20 | P a g e

6.Program to calculate factorial using user-defined function.

def calculateFact(n):
fact = 1 Output:
for i in range (1,n+1): Enter the number: 5
fact = fact * i Factorial of 5 is 120
print("Factorial of",num,"is",fact)
#function end here
num = int(input("Enter the number: "))
calculateFact(num) #function call

7.Program to find sum of first N natural number using user defined function
sum=1+2+3+4+-----------------------------------+N

def sumNatural(n): #function header


sum=0
for count in range(1,n+1):
sum=sum+count
print("The sum of first",n,"natural number is",sum)
#function end here
num=int(input("Enter the value of N:"))

sumNatural(num) #function call

output
Enter the value of N:5
The sum of first 5 natural number is 15

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 21 | P a g e

flow of Program to find the sum of three number without using functions
execution
[1] a=int(input("Enter first number:")) output
[2] b=int(input("Enter second number:")) Enter first number:10
[3] c=int(input("Enter third number:")) Enter second number:20
[4] sum=a+b+c Enter third number:30
[5] print("The sum of three number=",sum) The sum of three number= 60

Types of user defined function


There are four types of user defined function in Python
1. Function with no argument and no return value
2. Function with arguments and no return value
3. Function with no argument and with return values
4. Function with argument and with return values
Programs to find the sum of three number using above four types of user defined
function(UDF)
1. Function with no argument and no return value
program

 The function is called without passing argument by function call.


 The program control transfer to a called function and executes all the statements
present in it.
 Finally the control come back to the point of call in the program without any return
values.
def calculatesum():
Function heading
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
Control
transfer c=int(input("Enter third number:"))
to called
sum=a+b+c
function
print("The sum of three number=",sum)
Transfer control back
#end of function
to the point of call
calculatesum() without return values

#Function call by without passing arguments


value

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 22 | P a g e

2. Function with arguments and no return value


 The function is called by passing set of arguments values by function call.
 The program control transfer to a called function along arguments values .
 The parameters at the function heading receives the values of arguments passed.
Control  After that executes all the statements present in it.
transfer  Finally the control come back to the point of call in the program without any return
to called
function values.

along def calculatesum(x,y,z): #function heading


with
values sum=x+y+z
print("The sum of three number=",sum)
#end of function
Transfer control back to
a=int(input("Enter first number:")) the point of call without
return values
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
calculatesum(a,b,c)
#function call by passing arguments value

3.Function with no argument and with return values

 The function is called without passing argument by function call.


 The program control transfer to a called function and executes all the statements
present in it.
 Finally the control come back to the point of call in the program with return
values.

def calculatesum():
Function heading
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
Control
transfer sum=a+b+c
to called
function return sum Transfer control back
to the point of call
#end of function with return values
s=calculatesum() #function call by without passing arguments
print("The sum of three number=",s)

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 23 | P a g e

4. function with argument with return value

 The function is called by passing set of arguments values by function call.


 The program control transfer to a called function along arguments values .
 The parameters at the function heading receives the values of arguments passed.
 After that executes all the statements present in it.
 Finally the control come back to the point of call in the program with return values.

def calculatesum(x , y , z): #function heading


return (x+y+z)
#end of function
Transfer control
Control a=int(input("Enter first number:")) back to the point
transfer of call with return
to called b=int(input("Enter second number:")) values
function
c=int(input("Enter third number:"))
along
with result=calculatesum(a,b,c) #function call by passing arguments value
values
print("The sum of three number=",result)

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 24 | P a g e

Standard library function(Python standard library)


Q)What is python standard library?
Python has a very extensive standard library. It is a collection of many built in functions that
can be called in the program as and when required, thus saving programmer’s time of
creating those commonly used functions everytime.
Function can be of two type
1. Standard library function
a) Built-in function
b) module(collection of function)
2. User defined function

Built-in functions
Built-in functions are the ready-made functions in Python that are frequently used in
programs.

1. Input or Output 3. Mathematical Functions


 input()
 print()  abs()
2. Data type Conversion  divmod()
 int()  max()
 float()  min()
 bool()  pow()
 chr()  sum()
 ord()  len()
 tuple() 4. Other Functions
 list()
 str() __import__()
 set()  len()
 dict()  range()
 type()

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 25 | P a g e

Q)Explain any five mathmetical bultin functions in python

Function Description Example output


syntax (returns)
abs(x) It returns absolute >>> abs(-25) 25
value of number x >>> abs(25) 25

divmod(x,y) It returns tuple >>> divmod(5,2) (2,1)


(quotient , >>> divmod(8,4) (2,0)
remainder) >>> divmod(25,7) (3,4)

max(sequence) It returns largest >>> x=[10,20,30,40,50,60]


number in the >>> max(x) 60
sequence >>> str=”Rohit”
>>> max(str) ‘t’

min(sequence) It returns smallest >>> min(x) 10


number in the >>> str=”Rohit”
sequence >>> min(str) ‘R’

sum(sequence) It returns Sum of >>> sum(x) 210


all the elements in
the sequence

len(x) It returns Counts >>> len(x) 6


of element in x >>> str=”Rohit”
>>> len(str) 5

pow(x,y) It returns >>> pow(5,2) 25


X raise to the >>> pow(2,3) 8
power y(xy)

Note:- x, y and sequence are arguments

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 26 | P a g e

Q) What is module? How to import modules in python.


Module is a grouping of functions.
Or A module is a Python file that contains definitions of multiple functions.

 Use import statement to bring modules function to file

Syntax: Example: import math


import modulename import random
import statistics

 The functions in module can be called by following ways.

Syntax: modulename.functionname(arguments) Example: math.sqrt(64)

Q) Explain Built-in Modules in pythons


Python library has many built-in modules and many frequently used functions that
are found in those modules:
 Commonly used modules are
1. math 2. random 3. statistics

Q) Explain math module functions in python. NOTE

• import statement can be written


1.math module
anywhere in the program

• Module must be imported only once


 Math module contains different
types of mathematical functions. • In order to get a list of modules
available in Python,
1. ceil(x)
we can use the following statement:
2. floor(x)
3. fabs(x) >>> help("module")
4. factorial(x) • To view the content of a module say
5. fmod(x,y) math, type the following:
6. gcd(x,y)
>>> help("math")
7. pow(x,y)
8. sqrt(x,y) •The modules in the standard library can
9. sin(x) be found in the Lib folder of Python.

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 27 | P a g e

 In order to use the math module functions we need to import it using the following
statement:
import math

Function Description Example output


(Syntax) (return)
math.ceil(x) It return number >>> math.ceil(9.7) 10
greater than x >>> math.ceil (-9.7) -9
>>> math.ceil(9) 9
math.floor(x) It returns number >>> math.floor(4.2) 4
lesser than x >>> math.floor(-4.2) -5
>>> math.floor(4) 4
math.fabs(x) It returns absolute >>> math.fabs(6.7) 6.7
value of x >>> math.fabs(-6.7) 6.7
>>> math.fabs(-4) 4.0
math.factorial(x) It returns factorial of x >>> math.factorial(5) 120
>>> math.factorial(4) 24
math.fmod(x ,y) It returns remainder >>> math.fmod(5,2) 1.0
(x % y) >>> math.fmod(8,2) 0.0
>>> math.fmod(25,7) 4.0

math.gcd(x ,y) It returns greatest >>> math.gcd(10,2) 2


common divisor of x >>> math.gcd(25,45) 5
math.pow(x ,y) It returns x raise to the
>>> math.pow(3,2) 9.0
power y (xy) >>> math.pow(2,4) 16.0
>>> math.pow(5,3) 125
math.sqrt(x) Square root of x >>>math.sqrt(144) 12.0
>>> math.sqrt(64) 8.0
math.sin(x) Sine of x in radians >>> math.sin(0) 0
>>> math.sin(6) -.279
Note: Most of above functions in math module return a float value.

Q) Explain random module functions in python


2. random module
 This module contains functions that are used for generating random numbers.
 Random module contain following functions
1. random()
2. ranint(x,y)
3. ranrange(y)
4. ranrange(x,y)

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 28 | P a g e

 For using this module, we can import it using the following statement:
import random

Function syntax Description Example output


random.random() Random real >>> random.random() 0.65333522
number(float) in the
range 0.0 to 1.0
random. randint(x,y) Random integer >>>random.randint(3,7) 4
between x and y >>> random.randint(-3,5) 1
>>> random.randint(-5,-3) -5.0
random. randrange(y) random integer >>> random.randrange(5) 4
between 0 and y
(y is the stop value)
random. randrange(x,y) Random integer >>> random.randrange(2,7) 2
between x and y
(x is the start value
and y is the stop
value)

Q)Explain statistics module functions in pyhon


3. statistics module
 This module provides functions for calculating statistics of numeric (Real-valued)
data.
 The statistics module contain following following functions
1. mean(x)
2. median(x)
3. mode(x)
 For using this module, we can import it using the following statement
import statistics

Function name Description Example output

statistics.mean(x) Arithmetic >>>statistics.mean([11,24,32,45,51]) 32.6


mean
statistics.median(x) Middle >>statistics.median([11,24,32,45,51]) 32
value of x
statistics.mode(x) The most >>>statistics.mode([11,24,11,45,11]) 11
repeated >>>statistics.mode(("red","blue","red")) ‘red’
value

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 29 | P a g e

Q) Which statement is used to bring particular functions in a program?


from statement
To import specific functions in a program from a module, from statement can be used.

 The from statement loads only the specified functions instead of all the functions in
a module.
 Then directly call the function by its name and do not need to precede it with the
module name.
Syntax

from moduleName import functionname1 , functionname2,---------

Example:

>>> from math import sqrt , pow ,factorial


>>> sqrt(64)
8.0
>>>factorial(5)
120

Q) Create user defined module.

 We can also create our own module consisting of our own functions.
 Create some userdefined functions in a program then save those functions under a
module .
 A module is created as a python (.py) file containing a collection of function
definitions.
 To use a module, we need to import the module
 Python is case sensitive. All the module names are in lowercase.
What is docstring?
 add a docstring to describe the module. After creating module, import and execute
functions.
Program:Create a user defined module myMath that contain following user defined
function
1. add(x , y)
2. sub(x , y)
3. mult(x , y)
4. div(x , y)
Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science
Chapter-7 : Functions 30 | P a g e

 Type the four function functions in a file.


 Then save module name as myMath.py

“””myMath module What is Docstrings?

"""Docstrings""" is also called Python


This module contains functions, which documentation strings.
perform arithmetic operations on two
numbers and returns single value”””  Docstrings is a multiline comment
that is added to describe the
#Beginning of module modules, functions, etc.
 They are typically added as the first
def add(x,y):
line, using 3 double quotes.
return(x + y)
What is _doc_ variable?
def sub(x,y):
 __doc__ variable stores the
return(x - y) docstring.
 To display docstring of a module we
def mult(x,y): need to import the module and type
the following:
return(x * y)
>>>print(modulename.__doc__)
def div(x,y):
if y == 0:
print ("Division by Zero Error")
else:
return (x/y)
#end of module

Statements for using module myMath

>>> import myMath #Display descriptions of the said module


>>> myMath.add(20,30) >>> print(myMath.__doc__)
50 myMath module
>>> myMath.sub(100,40)
This module contains functions, which
60 perform arithmetic operations on two
numbers and returns single value
>>> myMath.mult(20,30)
600
>>> myMath.div(100,50)
2

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science


Chapter-7 : Functions 31 | P a g e

A)Programs using python standard library built functions and modules:


1. Write a program to find power of a number using built-in function.

program
output
x=int(input("Enter the base value:"))
Enter the base value:2
y=int(input("Enter the exponent:"))
Enter the exponent:4
result=pow(x,y) #function
The power of a number= 16
print("The power of a number=",result)

2. Write a program to find length of a string using built-in function.


str=input("Enter a string:") Output
count=len(str) #function call Enter a string:computer
print("The length of a string=",count) The length of a string= 8

3. Write a program to find factorial of a number using bulit-in module


function.

import math Output


num=int(input("Enter a number:")) Enter a number:4
result=math.factorial(num) #function call The factorial of a number= 24
print("The factorial of a number=",result)

4. Write a program to find square root of a number using bulit-in module


function.

import math output

num=int(input("Enter a number:")) Enter a number:64

result=math.sqrt(num) #function call The square root of a number= 8.0

print("The square root of a number=",result)

Suruchi Padhy (Mtech CSE, B.Tech IT ,Dip.ETC) Dept. of Computer Science

You might also like