7 Functions
7 Functions
Function: Function can be defined as a named group of instructions that accomplish a specific task when it is invoked.
Types of functions
Functions are divided into two category
1) User defined function
2) Standard library
a) Built-in functions
b) Modules
1) User defined function: A function defined by programmer, to achieve some task as per the programmer's requirement is called a user
defined function.
5) Function definition
This includes set of statements, which explains the task to be completed by that function.
A function definition begins with keyword def (short for define).
1
Computer Science Chapter 07 Functions
2) Function call: This statement includes name of the function, argument list within parenthesis to call a function.
Example:
def add(x,y): #function
c=x+y header
print("Sum is ",c) #function body
a=int(input(“Enter first number ”))
b=int(input(“Enter second number ”))
add(a,b) # function call
2
Computer Science Chapter 07 Functions
Output:
Enter first number 5
Enter second number 6
Sum is 11
add (4,3)
# value 4
and 3 are
arguments
a=5
Output
Sum is 7
b=3 #variables a and b are arguments
add
Example2:
Output (a,b
def add(x,y):
)Sum is 8
c=x+
Parameters: They variables used in function header, which receives the values from function call statement (calling function), are called as
parameters. print
Example: (“Su
m is
def add(x,y): #x and y are
“, c)
parameters c=x+y
print(“Sum is “,c)
3
Computer Science Chapter 07 Functions
a=5
String as parameter: Like numeric values, a string can also be passed as argument to a function.
Example:
def fullname(first,last):
fn = first + " " + last #+ operator is used to
concatenate strings print("Full name is ",fn)
Output
Enter first name: anil
Enter last name: kumar
Full name is anil
kumar
Default parameter: It is a parameter with a default value, which is predefined and assigned to the parameter (in function header) when
the function call does not have its corresponding argument.
Example: A python program to calculate area of circle, which includes default parameter concept.
def circlearea(r,pi=3.142):
area=pi*r*r
print("Area of circle is ",
area)
Output:
Enter the radius of circle 5
Area of circle is 78.55
Note:
Default parameter value
can be overwritten by
passing value for default
parameter in function call.
Expressions can also be
Example1:
used as function
def simpleinterest
argument. (principal=1000, rate, time=5): #incorrect
If expressions are used as
Example2:
function arguments, then
def simpleinterest
the expression(rate,
is principal=1000, time=5): #correct
evaluated first, before
Functions Returning
calling Value
the function.
After completing the task, a function may display result or return a value (result).
The value for a default
The return should
parameter statement be returns the values from the function.
If
assigned from
a function right no
return to left
value then such functions are called void functions.
The
in the function
return header.does the following:
statement
1) returns the control to the calling function.
2) return value(s) or None.
Example:
def add():
a=2
b=3
c=a+b
return c # return statement
result=add()
print("Sum is",result)
Output:
Sum is 5
5
Computer Science
Chapter 07
Functions
Based on argument list and return statement a programmer can have the function in either of the following ways (arguments and return
statements are optional)
Calling function: A function that transfers control to another function, by specifying name of that function and arguments is called as
calling function.
Example:
def add(x,y):
Called function: # called
It is a function which receives the call and arguments from calling function are called as, called function.
result=x+y function
print("Sum is", result)
Flow of Execution
Flow of execution can be defined as the order in which the statements in a program are executed.
The Python interpreter starts executing the instructions in a program from the first statement, one by one, in the order of
appearance from top to bottom.
The statements inside the function are not executed until the function is called.
6
Computer Science
Chapter 07
Functions
When the interpreter encounters a function call, the control jumps to the called function and executes the statement of that
function.
After that, the control comes back to the point of function call so that the remaining statements in the program can be executed.
It is important to note that a function must be defined before its call within a program.
[2] def add():
[3]The followinga=2
Example: example shows the flow of execution of statements when a function is used
[4] b=3
5 c=a+b
6 return c # return statement
[1] [7] result=add()
[8] print("Sum is",result)
Output:
Sum is 5
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
defined inside
a function
cannot be
accessed
outside it.
Every variable
has a well-
defined
accessibility.
2) Local Variable
A variable that is defined inside any function or a block is known as a local variable.
It can be accessed only in the function or a block where it is defined.
It exists only until the function executes.
Example1:
g=10 #g is global variable with global scope
def add():
x=2 # x is local variable with local scope
# y is local variable with local scope
y=3
res
print("Sum is",result)
add() ult
=x+
Output: y+g
Sum is 15
Example2:
g=10
def add():
g=4 # g is used as local variable and hides global variable g
x=2
y=3
result=x+y+g
print("Sum is",result)
Output:add()
Sum is 9
8
Computer Science Chapter 07 Functions
Example3:
g=10
def add():
global g # g is used as global variable
x=2
y=3
resglo=x+y+g # g is used as global variable
print("Sum is",resglo)
g=4 # g is used as local variable
resloc=x+y+g # g is used as local
print("Sum is",resloc) variable
add()
Output:
Sum is 15
Sum is 9
Built-in functions
Built-in functions are the ready-made functions in Python that are frequently used in programs
The set of instructions to be executed for these built-in functions are already defined in the python interpreter.
9
Computer Science Chapter 07 Functions
>>> max(23,4,56)
56
x, y, z,.. may be integer or floating point number Smallest number in >>> min([1,2,3,4])
the sequence/ smallest of two 1
or more arguments >>> min("Sincerity")
min(sequence) 'S'
or
min(x,y,z,...) #Uppercase letters have
lower ASCII values than
lowercase letters.
>>>
min(23,4,56) 4
x, y, z may be integer or floating point number xy (x raised to the power y) >>> pow(5,2)
if z is provided, then: (xy ) % z 25.0
pow(x,y[,z]) >>>
pow(5.3,2.2)
39.2
>>> pow(5,2,4)
1
x is a numeric sequence and num is an optional Sum of all the elements in the >>> sum([2,4,7,3])
argument sequence from left to right. 16
sum(x[,num]) if given parameter, num >>>
is sum([2,4,7,3],3)
added to the sum 19
>>> sum((52,8,4,2))
66
x can be a sequence or a dictionary Count of elements in x >>> len(“Patience”)
8
>>> len([12,34,98])
3
len(x) >>> len((9,45))
2
>>>len(,1:”Anuj”,2:
”Razia”,
3:”Gurpreet”,4:”Sandra”-)
4
11
Computer Science Chapter 07 Functions
Module
A module is a group of functions.
A module is created as a python (.py) file containing a collection of function definitions.
To use functions created in a program in another program, save these functions under a module and reuse them.
To use a module, we need to import the module into program.
Calling a function in a 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.
Built-in Modules: Python library has many built-in modules that are really useful to programmers.
Some commonly used modules and functions of that module are listed below
1) math
2) random
3) statistics
4) math module
It contains different types of mathematical functions.
Most of the functions in this module return a float value.
In order to use the math module , import it using the following statement:
import math
12
Computer Science Chapter 07 Functions
>>> math.floor(-4.5)
-5
x may be an integer or >>> math.floor(4.5)
math.floor(x) floating point floor value of x 4
number >>> math.floor(4)
4
>>> math.fabs(6.7)
x may be an integer or 6.7
math.fabs(x) floating point absolute value of x >>> math.fabs(-6.7)
number 6.7
>>> math.fabs(-4)
math.factorial(x) x is a positive integer factorial of x >>>
math.factorial(5)
200
>>> math.fmod(4,4.9)
4.0
x and y may be an >>>
math.fmod(x,y) integer or floating point x % y with sign of x math.fmod(4.9,4.9)
number 0.0
>>> math.fmod(-
4.9,2.5)
-2.4
>>> math.fmod(4.9,-4.9)
0.0
>>> math.pow(4,2.5)
32.0
>>> math.pow(6.5,2)
42.25
>>>
math.pow(5.5,3.2)
233.97
x may be a positive >>> math.sqrt(144)
math.sqrt(x) integer or floating point square root of x 12.0
number >>> math.sqrt(.64)
0.8
x may be an integer or >>> math.sin(0)
floating point number in 0
math.sin(x) sine of x in radians
radians >>> math.sin(6)
-0.279
2) random module
This module contains functions that are used for generating random numbers.
To use this module, import it using the following statement.
import random
random. y is a positive integer signifying the Random integer between 0 and y >>>
randrange(y) stop value random.randrange(5) 4
random. x and y are positive integers signifying Random integer between x and y >>>
randrange(x,y) the start and stop value random.randrange(2,7) 2
3) statistics module
This module provides functions for calculating statistics of numeric (Real-valued) data.
It can be included in the program by using the following statement.
import statistics
Commonly used functions in statistics module
Function Syntax Argument Return Example
Output
>>> statistics.
statistics.mean(x) x is a numeric sequence Arithmetic mean mean([11,24,32,45,51]
) 32.6
>>>statistics.
statistics.median(x) x is a numeric sequence Median (middle value) of x median([11,24,32,45,51]
)
32
>>> statistics.
mode([11,24,11,45,11]
) 11
statistics.mode(x) x is a sequence Mode (the most repeated value) >>> statistics.
mode((“red”,”blue”,”red”))
‘red’
Note:
• import statement can be written anywhere in the program
• Module must be imported only once.
• In order to get a list of modules available in Python, use the following statement:
>>> help("module")
• To view the content of a module say math, type the following:
>>> help("math")
15
Computer Science
Chapter 07
Functions
from Statement
Instead of loading all the functions into memory by importing a module, from statement can be used to access only the required
functions from a module.
It loads only the specified function(s) instead of all the functions in a module.
To use the function when imported using "from statement", no need to precede it with the module name, instead directly call the
function.
Syntax: >>> from random import random
>>>
>>> random()
from modulename import functionname #Function called without the module name
[,functionname,...]
ExampleOutput:
1:
0.979
63525046083
87
Example 2:
>>>
from math
import
ceil,sqrt
Composition: >>>
value =
A programming statement wherein the functions or expressions are dependent on each other’s execution for achieving an output is
ceil(624.7)
termed as composition.
>>> sqrt(value)
Output:
Examples of composition:
25.0number: "))
1) a = int(input("First
2) print("Square root of ",a ," = ",math.sqrt(a))
3) print(floor(a+(b/c)))
4) math.sin(float(h)/float(c))
16
Computer Science Functions
Chapter 07
Output:
>>> import basic_math
>>> print(basic_math. doc )
basic_math Module
*******************
This module contains basic
arithmetic
operations that can 17
be carried out on
Computer Science Chapter 07 Functions
"""Docstrings"""
It is also called Python documentation strings.
It is a multiline comment that is added to describe the modules, functions, etc.
They are typically added as the first line, using 3 double quotes.
doc variable stores the docstring.
To display docstring of a module it is required to import the module and type the following:
print(<modulename>. doc ) # are 2 underscore without space
Example:
>>> print(math. doc )
18