Chapter 2 - Functions in Python NEW
Chapter 2 - Functions in Python NEW
FUNCTIONS
CHAPTER – 2 (XII – C.Sc.)
LECTURE NOTES BY : DEEPIKA RATHOUR
INTRODUCTION
Python provides the feature to divide a large program into different smaller modules.
These modules are known as functions which work upon data for processing. It is
difficult and time consuming to interpret a large program every time there is a slight
modification in the code.
But if that program is divided into a number of small functions (also called sub-
programs), then the whole task becomes easy and saves a lot of time and effort.
One Long Program : In this program, the task has been divided into smaller tasks,
each of which is performed by a separate Function
1. Program Development Made Easy and Fast : Work can be divided among project members thus implementation
can be completed fast.
2. Program Testing Becomes Easy : Work can be divided among project members thus implementation can be
complete d fast.
3. Code sharing becomes possible : A function may be used later by many other programs, this means that a python
programmer can use function written by other, instead of starting over from scratch.
4. Code Reusability Increases : A function can be used to keep away from rewriting the same block of codes which we
are going to use at two or more locations in a program. This is especially useful if the code involved is long or
complicated.
5. Increases Program Readability : It makes possible top down module programming. In this style of programming,
the high level logic of the overall problem is solved first while the details of each lower level function is addressed later.
The length of the source program can be reduced by using functions t appropriate places.
6. Function Facilitates Procedural Abstraction : Once a function is written, it serves as a black box. All that a
programmer would have to know to invoke a function would be to know its name, and the parameters that it expects.
7. Function Facilitates the Factoring of Code : A function can be called into other functions and so on…..
CTM :
Functions are the most important building blocks for any Python program and
work on the Divide and Conquer approach.
Built-in Functions
Modules
User-defined
1 2 3
Built-in Modules User-defined
Functions Functions
1
Built-in
Functions
1. BUILT-IN FUNCTIONS :
(ii) float( ) : float function converts integer and strings into floating point numbers.
If no argument is passed,
float( ) returns 0.
i) If argument is a number float() returns the same number as a float. e.g. float(26) returns 26.0 & float(21.76) as 21.76.
ii) If argument is an expression, the expression is evaluated, and float() returns its value. e.g. float(50+30) returns
80.00 and float(12+3/4) returns 12.75 and in some cases 12.00 only.
iii) If argument is a string containing +/- sign and a floating point number in correct format, float( ) returns the float value
represented by this string, e.g. float(‘3.14149’) returns 3.14159.
iv) If string argument contains any character other than leading +/- sign and floating point number in correct
format, then float( ) results in an error, e.g. float(‘40.6.3’), float(‘86.7-’), float(‘35+4/7’) will result in errors.
(b) Input Function : Input( ) function accepts an input string from the user without evaluating its value. input( ) function
continues to read input text from user until it encounters as new line.
For Example name = input(‘Enter Your Name : ‘)
: print(‘Welcome’, name + ‘Pleasure to meet
you’)
(c) eval function : eval( ) evaluates the value of a string. eval( ) function accepts a string as an argument and returns
the numeric result (int or float) after evaluating the string as a number.
whose
len() function returns the length of an object (i.e. round( ) function rounds a given floating point number to
number of items it hold). It may be a sequence (string, the specified number of digits and returns the result. The
tuple or list) or mapping (dictionary). number itself remains unchanged.
n, number expression to be rounded,
Syntax : round (n, p) p, number of digits up to which n is to be rounded.
Starting and ending numbers can be explicitly defined by specifying the two
arguments for beginning and ending numbers :
Syntax : range(begin, end)
For Example : >>> range(5, 9)
To show the : >>> list(range(5,9))
list [5, 6, 7, 8]
2
Modules
2. MODULES
Module is a file containing functions and variables defined in separate files. When a
program is broken into modules, each module should contain functions that perform
related tasks.
Libraries : are some commonly used modules in Python that are used for certain
predefined tasks.
With the use of Modules same code can be used in more than one program. If a set of
functions is needed in other programs, we can place those functions in module and then
can import the module in a program that needs to call one of the functions.
Once a module is imported, we can refer to any of its functions or variables in our
program.
Functions are the most important building blocks of any application in Python and
work on Divide and Conquer approach.
Importing Modules in a Python Program...........Contd.
In order to access any function present in imported module, specify the name of module followed by the
name of function, separated by dot (.) called dot notation.
For example : result = math.sqrt(64) # gives output as 8 which gets stored in variable ‘result’.
In the above example sqrt( ) function belongs to math module which accepts an argument and returns the
square root of the argument.
Above statement calls the sqrt( ) passing 64 as an argument and returns the square root of the number
passed as argument i.e. 8. which is then assigned to variable ‘result’.
Few functions from math module :
ple
sqrt function
sin function
math module in Python
Interpreter cos function
…..
Source Code
import math # the very first statement to be given
ceil(x) : returns the smallest integer that is greater than or equal to x.
For : print(“math.ceil(3.4) : “, math.ceil(3.4))
example : math.ceil(3.4) : 4
Output
floor(x) : returns the largest integer that is less than or equal to x.
>>> math.floor (-45.17)
-46.0
>>> math.floor (100.12)
100.0
help function
cos(x) : returns: the
Python help()
cosine of x library function is extremely relevant to know the purpose of a function & its
in radians.
use.
>>> math.cos(3)
-0.9899924966004454
>>> math.cos(-3)
-0.9899924966004454
>>> math.cos(0)
1.0
>>> math.cos(math.pi)
-1.0
import statement is the first statement to be given in a program for generating random
numbers
import random
The various functions associated with the module are explained as follows :
randrange ( ) : method generates an integer between its lower and upper argument. By default, the lower argument is 0
and upper argument is 1.
For Example : ran_number = random.randrange(30)
Program to calculate the sum of the digits of a random three-digit number
Explanation :
The random( ) function generates a fractional number from 0 to 1. When a random number
generated using random( ) gets multiplied by 900, a random number is obtained from 0 – 899.
When we add 100 to it, we get a number from 100 to 999.
Then, the fractional part gets discarded using int( ) and gets printed on the shell windows. In the
next statement, the first digit (the most significant) of the number is extracted by dividing it with
100 (a = n // 100).
The digit at one’s place is extracted by dividing the number by 10. The number obtained as the
quotient further takes mod with 10 to extract its last digit which is the same as the digit placed in
the middle of the original number. For extracting each digit of the number, division by 10 (c = n
%10) is carried out.
In the last statement, the sum of the digits is calculated and displayed on the screen.
randint( )
This function generates a random integer number between two given numbers.
This function accepts two parameters, a and b, as the lowest and highest number; returns a number ‘N’ in the inclusive
range [a,b]; which means a<=N<=b,. This function is best suited for guessing number applications.
Syntax : random.randint(a,b) # Here ‘a’ is the lower bound and ‘b’ is the upper
bound. Prg. Example : To generate a number between 0 and 9.
Prg. Example : Program that fills a list with numbers (Using randint( ))
uniform( ) choice( )
This method generates a random floating-point This method is used for making a random selection
number in between two numbers. from a sequence like list, tuple, or string.
Syntax : random.uniform(x,y) Syntax : random.choice(sequence)
Here ‘x’ is the lower bound and ‘y’ is the upper bound
of random float. The returned random floating point
number is greater than or equal to x and less than y.
3
User-defined
Functions
shuffle( )
This method is used to shuffle or swap the contents of a list (generate a random permutation of a list in-place.
Syntax : shuffle(list)
Here, list could be an array/list or tuple but returns reshuffled list.
3. USER DEFINED FUNCTIONS
User Defined Functions are defined by the programmer. As a programmer you can create
your own functions.
How to define and call a function in Python
As we know a user-defined function is created by the def statement followed by the function name and
parentheses( ). This can be explained with the help of following example.
def function_name(comma_separated_list_of_parameters):
“””docstring”””
statement
Function Definitions
Keyword statement
.
.
Statements below def begin with four spaces. This is called indentation. It is a requirement of
Python that the code following a colon must be indented.
Components of Function Definition
Note :
Return without an expression argument is
used to return from the middle of a
function in which case the NONE value is
returned.
Argument is a value passed to the function when it is called or we can say that arguments are the value(s) provided in
function call/invoke statement.
(a) def product(a,b): Function definition is valid as the parameters passed are valid
print(a*b) variable names.
(b)def product(a+1,b): Function definition is invalid as the expression (a+1) has been
print(a*b) passed as an argument which is illegal in Python..
(c) def product(5,’b’): Function definition is invalid as 5 and ‘b’, which are literals, are
print(a*b) passed as the parameter which is illegal in Python..
If there is a function with many parameters and we want to specify only some of them in function call, then value if
such parameters can be provided by using their name, instead of the position (order). This is called keyword
arguments.
Types of Arguments :
Types of arguments provided by Python :
def f1(x,y) : # x, y are formal arguments
1. Positional Arguments :
You must remember that, the order of arguments is not important but the number of arguments must be matched.
Keyword arguments are the named arguments with assigned values being passed in the function call statement
Advantages of writing functions with Keyword Arguments :
i) It is very easy to use the function with keyword arguments as we do not need to remember the order of arguments.
ii) We can specify values of only those parameters which we want to, as other parameters have default argument
values.
While using Keyword Arguments, the following points should be kept in mind :
i) An argument list must have positional arguments followed by any keyword.
ii) Keywords in arguments list should be from the list of parameters name only.
iii) No parameter should receive value more than once.
iv) Parameter names corresponding to positional arguments cannot be used as keywords in the same calls.
4. Variable Length Arguments :
In certain situations , we can pass variable number of arguments to a function. Such type of arguments are called variable
length arguments/parameters.
Variable length arguments are declared with * (asterisk) symbol in Python as :
>>> def f1(*n)
The asterisk (*) character has to precede a variable identifier in the parameter list.
This can be called by passing any number of arguments, including zero number. Internally, all these values are represented
in the form of a tuple.
Anything calculated inside a function but not specified as an output
quantity will be deleted once the function stops running.
In the program :
i) Input is obtained as string and elements are
returned asa list of strings using split()
method.
ii) The counting of inputted elements is done
using len() method.
iii) Each element is added in the list ‘a’ and
passed as argument to the list_avrg(lst),
which calculates the sum of elements in list.
iv) Each element returned as string using split() is
typecast using the statement a[i] = int(a[i])
and then it is passed as an argument to
list_avg() method.
SCOPE OF VARIABLES
Scope of variables refers to the part of the program where they are legal and accessible. Scope holds the current set of
variables and their values.
There are broadly two types of scope of variables : Global Scope and Local Scope
Global Scope :
A name declared in top level segment (_main_) of a program is said to have a global scope and is usable inside the whole
program and all blocks (functions, other blocks) contained within the program.
Local Scope :
A name declared in a function body is said to have local scope. It can be used only within this function and the other
blocks contained under it. The names of formal arguments also have local scope.
Program to compute the area of a rectangle taking Length and Breadth as input as the arguments to the function:
b) Recursion terminates when a base case is b) Iteration terminates when the loop
recognized. continuation finishes.
c) Recursion causes another copy of function c) Iteration normally occurs within a loop sp
and hence a considerable memory is lost. the extra memory assigned is ommited.