0% found this document useful (0 votes)
21 views

7 Functions

Uploaded by

paiprashanth92
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

7 Functions

Uploaded by

paiprashanth92
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Computer Science Chapter 07 Functions

Chapter 7 Functions 09 marks (1+1+2+5)


Modular programming:
The process of dividing a computer program into separate independent blocks of code or separate sub-problems with different
names and specific functionalities is known as modular programming.

Function: Function can be defined as a named group of instructions that accomplish a specific task when it is invoked.

The Advantages of Function


• Increases readability of the program, the program is better organised and easy to understand.
• Reduces length of program and makes debugging easier.
• Increases reusability, as function can be called multiple times.
• Work can be easily divided among team members and completed in parallel.

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.

Creating User Defined Function


Following steps are used in user defined function creation
3) Function definition
4) Function call

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

The syntax for creating a user defined function is as follows:

def <function name> ( * parameter 1, parameter 2,…….+ ):  function header


Set of instructions (statements) to be executed
[ return <value> ] function
body, should be indented within function header

In the above syntax


 The items enclosed within square brackets [ ], in function header, are
called as parameters and they are optional.
 Function header always ends with colon ( : ).
 Function name should be unique and it is an identifier.
 The return statement returns a value to calling function or function
Example:call statement.
 The statements
def add( ): outside#function
the function indentation are not considered as
header
part of the
a=2 function.
b=3
c=a+b #function body
print("Sum is: ",c)

add() # function call


Output:
Sum is: 5

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

Arguments and parameters


Argument: it is a value or
variable passed to the called
function during function call.
Example1:
def add(x,y):
c=x+y
print
(“Su
m is
“, c)

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

b=3 # a and b are arguments


Outputadd
(a,b
Sum is 8
Note: if)arguments and parameters refer same value (object), they will have the same identity.

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)

first = input("Enter first name: ")


last = input("Enter last name: ")
fullname(first,last) #function call

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)

r1=float(input("Enter the radius of circle "))


circlearea(r1)
4
Computer Science Chapter 07 Functions

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)

1) Function with no argument and no return value.


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

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)

def read(): # calling function


a=5

b=8 #function call


add
read() (a,b #function call
)
Output:
Sum is 13

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.

A variable can have


Computer Science Chapter 07 Functions

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

PYTHON STANDARD LIBRARY


 Standard library is a collection of many built in functions that can be called in the program as and when required.
 And thus saving programmer’s time of creating those commonly used functions every time.

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

List of built-in functions


Input
or Data type Mathematica
Conversion l Functions Other Functions
Output
input( ) bool( ) abs( ) import ( )
print( ) chr( ) divmod( ) len( )
dict( ) max( ) range( )
float( ) min( ) type( )
int( ) pow( )
list( ) sum( )
ord( )
set( )
str( )
tuple( )

Function Arguments Returns Example


Syntax Output
x may be an integer or floating point Absolute value of x >>> abs(4)
abs(x) number 4
>>> abs(-5.7)
5.7
x and y are integers A tuple: >>> divmod(7,2)
(quotient, remainder) (3, 1)
divmod(x,y) >>>
divmod(7.5,2)
(3.0, 1.5)
>>> divmod(-7,2)
(-4, 1)
x,y,z,.. may be integer or floating point number Largest number in the sequence >>>
max(sequence)
or / largest of two or more max([1,2,3,4]) 4
max(x,y,z,...) arguments >>>
max("Sincerity")
'y' #Based on 10
ASCII value
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.

The syntax of import statement is as follows:


import modulename1 *,modulename2, …
+

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.

The syntax is as shown below:


modulename.functionname(
)

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

List of Commonly used functions in math module


Function Arguments Returns Example
Syntax Output
>>> math.ceil(-9.7)
-9
x may be an integer or >>> math.ceil (9.7)
math.ceil(x) floating point ceiling value of x 10
number >>> math.ceil(9)
9

>>> 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.gcd(x,y) x, y are positive integersgcd (greatest common >>>


divisor) of x and y math.gcd(10,2) 2
math.pow(x,y) x, y may be an integer or xy (x raised to the >>> 13
floating point number power y) math.pow(3,2) 9.0
Computer Science Chapter 07 Functions

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

Commonly used functions in random module


Function Argument Return Example
Syntax Output
random.rando No argument (void) Random Real Number (float) in >>>
m() the random.random()
range 0.65333522
0.0 to 1.0
random. x, y are integers such that x <= y Random integer between x and y >>> random.randint(3,7)
randint(x,y) 4
>>> random.randint(-3,5)
1
>>> random.randint(-5,-
3)
-5.0
14
Computer Science Chapter 07 Functions

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

Creating user defined module


Following program creates a user defined module basic_math that contains the following user defined functions:
1. To add two numbers and return their sum.
2. To subtract two numbers and return their difference.
3. To multiply two numbers and return their product.
4. To divide two numbers and return their quotient
5. Also add a docstring to describe the module.
Program:
"""
basic_math Module
*******************
This module contains basic arithmetic
operations that can be carried out on
def addnum(x,y): numbers #Beginning of module
""" return(x + y)
def subnum(x,y):
retur
n(x - y)
def
multnum(x,y):
return(x * y)
def divnum(x,y): print ("Division by Zero Error")
else: if y
== 0: return (x/y) #End of module

 save the above program with name basic_math.py

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

>>> a = basic_math.addnum(2,5) #Call addnum() function of the


>>> print(a) #basic_math module
7

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

You might also like