Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 58

User-Defined Functions (UDFs) in Python are called

using only the function name.

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.

If required and if it becomes necessary, the sub-programs (or sub-problems can be


further divided into still smaller programs, and the process of dividing a program into a
set of programs of smaller size can be continued up to any appropriate level.

Therefore, functions provide a systematic way of problem-solving by dividing the given


problem into several sub-problems, finding their individual solutions, and integrating
the solution of individual problems to solve the original problem.

This approach to problem-solving is called Stepwise Refinement Method or Modular Approach


or
Divide and Conquer Approach.
Using Functions to Divide and Conquer a large task.

One Long Program : In this program, the task has been divided into smaller tasks,
each of which is performed by a separate Function

Statements def function1 ( ) :


Statements statement
Statements function
statement
Statements
statement
Statements
Statements
def function2 ( ) :
Statements statement
Statements function
Statements statement
Statements statement
Statements
Statements def function3 ( ) :
statement
Statements
function
Statements statement
Statements statement
Statements
FUNCTIONS
1) A function is a group of statements or programming block of
codes that perform a single, related task.
2) It runs only when it is called.
3) We can pass data known as parameters, into a function.
4) A function can return data as result.
5) We have already used some inbuilt functions like print( ) etc.
6) A user can also create a function according to its requirements
and these functions are known as user-defined functions.
Advantages of Using Functions

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.

Functions can be categorized into the following three types :

 Built-in Functions

 Modules

 User-defined
1 2 3
Built-in Modules User-defined
Functions Functions
1
Built-in
Functions
1. BUILT-IN FUNCTIONS :

Built-in functions are the pre-defined functions that are


already available in Python. Python has many useful
built-in functions to make programming easier, faster
and more powerful.
Built-in functions are available in the standard library and
the programmer don’t have to import any module (file)
for using them.
Some Built-in Functions in Python :
(a) Type Conversion Functions : Type Conversion functions convert values from one type to another.
(i) int ( ) : The int function takes any value and converts it to integer (Statement 1). int( ) can convert floating-point
values to integers without rounding off; it chops off the fraction part (Statement 3 & 4). However, if we give a string
value as an argument to int( ), it will generate an error (Statement If no argument is passed, int( ) returns 0.
5).
(ii) str( ) : The str( ) function converts its argument into string (Statement 2).

Statement 1, Converts the string arguments to integer,

Statement 2, Converts the numeric value to strings,


Type Conversion Functions
Statement 3, Converts the floating argument to integer, in Python
Statement 4, Chops of floating point number to integer,

Statement 5, Generates the error if the argument is a string


value,
Some Built-in Functions in Python..............Contd.

(ii) float( ) : float function converts integer and strings into floating point numbers.

If no argument is passed,
float( ) returns 0.

float function treats different types of parameters as follows :

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.

If the given argument is not a string, or if it cannot be evaluated as number, it results in an


error.
For Example x = eval(‘55 + 55’)
: print(x)
(d) min and max functions : Used to find minimum and maximum value respectively from several given values.

The above code line prints ‘Python’ as the output, because


two or ‘P’
mini(‘interesting’)
function : takes
item.
more arguments
max functionand
: returns the smallest
respectively.
(an uppercase letter) has the smallest ASCII value i.e. ’80’,
which is less than the other lowercase words : i (‘is’); v(‘very’); takes two or more arguments and returns the largest item.

whose

ASCII values are 105, 118, 105


(e) abs function : (f) Type function :
abs( ) function takes an integer or float as argument and type( ) function is used to determine the type of a
returns absolute value (positive value) of a single variable (value it holds/point s to).
number.

Boolean argument given to type() should have T


& F in uppercase for True and False respectively;
otherwise it will generate an error.
(g) len() function : (h) round() function :

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.

‘n’ is mandatory argument and can be integer or float while


‘p’ is an optional argument and must be an integer.
(i) range() function :
range() function is used to define a series of numbers and is particularly useful in ‘for loops’:
For example :

The above examples of range() demonstrated an increment of 1. Increment


The expression range(5) above generates a series of integers from 0 to 4 (5- can be changed by introducing a third argument, ‘step’. It can be a negative or
1). positive number, but never zero.
To show the list of numbers, use command list(range(n)) :
Syntax : range(begin, end, step)
For Example : >>> range(10, 71, 5)
To show the : >>> list(range(10, 71, 5))
list [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70]

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.

A module in Python is a file that contains a collection of related functions.


Importing Modules in a Python Program
Two important methods to import modules in a python program are :
i) import statement : To import entire module
ii) from : To import all functions or selected ones.
import : To use modules in a program, we import them using import statement.
Syntax : import modulename1 [modulename2, …….]
For example : import math
On execution of above statement , Python performs the following operations :
a) Search for the file “math.py”
b) Create space where modules definitions and variable will be created.
c) Execute the statements in the modules.
a) In this way, the module definition will become part of code in which the module was imported.

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

pow(x,y) : returns the value of XY, where X and Y are numeric


For expressions.
example : print(“math.pow(3,3) : “, math.pow(3,3,))
Output : math.pow(3,3,) : 27
fabs( ) : returns the absolute value (positive value) of expression/number.
>>> import math # to import math module
>>> print(‘Absolute Value = ‘, math.fabs(-15))
Absolute Value : 15.0
To illustrate sqrt( ) function of math library.
Ques. Write a python module to display square root of a number using Math module.
log10(x) : returns the base – 10 logarithm of x.
>>> print(“math.log10(100) : “, math.log10(100))
math.log10(100) : 2.0
>>> math.log10(100.12)
2.00052084094361854

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


>>> print (help(math.cos)) cos (x)
Help of built-in function cos in module math : Returns the cosine of x (measured in radians).
cos(…)
String Module :
random module (Generating Random Numbers) :
In programming concepts random modules are used as two approaches :
(a) Deterministic Approach : When aware of definite output to be obtained
(b) Non-deterministic Approach : Certain situations/applications that involve games or simulations.

In these types situations, random numbers are extensively used as such as :


i. Pseudorandom numbers on Lottery scratch cards.
ii. Recaptcha (like, in login forms) uses a random number generator to define which image is to be shown to
the user.
iii. Computer games involving throwing of dice, picking a number, or flipping a coin.
iv. Shuffling deck of playing cards, etc.
In Python, random numbers are not enabled implicitly; therefore, we need to invoke random module
explicitly or to invoke random code library in order to generate random numbers.

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

1) def keyword marks the start of function header.


2) A function name to uniquely identify it.
3) Parameters (arguments) through which we pass values to a function. They
are optional.
4) A colon [:] to mark the end of function header.
5) Optional documentation string (docstring) to describe what the function
does.
6) Function body comprises of one or more Python valid statements.
Statements must have the same indent level of 4 spaces.
7) An optional return statement to return a value from the function.
Significance of Indentation (Space) in Python
Python functions don’t have any explicit beginning or end, like curly braces to indicate the start and stop for the function,
they have to rely on this indentation.
If we write “print” function right below the def func1( ), it will show an “Indentation error : expected an indented block”.

Improper Indentation results in error generation

Error removed by making proper Indentation before


print() function.
Atleast one indent is enough to make our code work
successfully.
When we call another statement which is still in function in the same program, we maintain the same indent for rest of
the code and if it is not declared right below first print statement it will display error “unindent does not match any other
indentation level” . Also check the output of the following program.
Ques. : Write a user defined function to print a right-angled triangle

Invoking the Function


HOW FUNCTION RETURNS A
VALUE
Till now we were discussing user-defined functions which were not returning any value to the calling function or Python
interpreter. Now, we shall discuss the functions with some return values.
Syntax def function_name(arguments) Here return command specifies the values to
: return <value> be returned to the calling function.

Example : Python function to compute area of triangle.


Example : Function to find the factorial of a number.
Example : Program to find the roots of a Quadratic Equation.

Note :
Return without an expression argument is
used to return from the middle of a
function in which case the NONE value is
returned.

return statement returns the


value of an expression following
the return keyword.

In the absence of return


statement, the default value
None is returned.
PARAMETERS AND ARGUMENTS IN FUNCTIONS
:
Parameters are the value(s) provided in parentheses of function header. If there are more than one value required by the
function, then they are listed in parameter list separated by comma as show below.

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.

Arguments in Python can be of these value types : literals


or variables or expressions – but the Paramemters have to
be some name (Variables to hold some values; Literals or
Expressions can not be used as parameters.
A few things to remember for parameter passing :
In Python Functions :
i) If you are passing values to immutable types i.e. Numbers, strings etc., to the called function, then the called function
cannot alter their values.
ii) In case parameters passer are of mutable types, such as list or dictionaries, then called function would be able to
make changes to them.
Example : Given below are some function definitions. Identify which of these are invalid giving reasons.

(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

f1(20,30) # 20, 30 are actual arguments


Only four types of Formal Arguments are allowed in Python :
i. Positional Arguments
ii. Default Arguments
iii. Keyword Arguments
iv. Variable Length Arguments

1. Positional Arguments :

Positional arguments are arguments in which number


and position of arguments must be matched. If we
change the their order, then the result will be
changed.

If we change the number of arguments passed, then it


shall result in an error.
A default argument is an argument that assumes a default value if a value is not provided in
2. Default Arguments :
the function call for that argument.

If default arguments are passed to a


function, then non-default arguments
should not be taken, otherwise it will result
in an error as shown in figure :
3. Keyword Arguments :
When we have a function with many arguments with many parameters and want to specify only some of them in function call, then
value for such parameters can be provided by using their name instead of the position (order). Such arguments are called Keyword
Arguments or Named Arguments.
Using Keyword Arguments, we can pass argument values by keyword, i.e., by Parameter name.

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.

Example : Consider the following function definition :


def fun(a, b=1, c=5):
print(“a is”, a, “b is”, b, “c is”, c)

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.

For example, >>> def f5(x,y):


>>> a = x+y
>>> b = x-y
>>> return a**2, b**2
…….
>>> f5(3,2)
If we try to call a or b, an error message will be displayed.
>>>a
PASSING ARRAYS/LISTS TO FUNCTIONS
Array in Python are lists that can contain mixed data types. The numarray module contains support for true arrays.
For proper implementation of arrays, Numpy library/interface is required. But, here we shall be implementing lists as
arrays using Python Shell.
In comparison to Arrays, which contain elements of same data types Lists are better as they may hold elements of several
data types which make them much more flexible and faster than arrays..

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.

Example : Consider the following Python program : In the program :


i) Three variables num1, num2 and sum
1. def calcsum(x,y):
2. Z = x + y #statement-1 (Global Variables) are defined in the main
3. return z #statement-2 program and three variables x, y and z
(Local Variables) are defined in the
function
4. num1 = int(input(“Enter First Number : “)) #statement-1 calcsum().
5. num2 = int(input(“Enter Seconds Number : “)) #statement-2
#statement-3
Scope of names num1, num2 and sum is Global
6. Sum = calcsum(num1, num2)
7. print(‘Sum of given numbers is : ‘,sum) #statement-4 are and scope of names x, y and z Local.
USING main( ) AS A FUNCTION
Including a main( ) function is not mandatory in Python. It structures a Python program in a logical way which puts the
most important components of the program into one function.

Program to compute the area of a rectangle taking Length and Breadth as input as the arguments to the function:

Every Python module has a built-in variable called name .


When module itself is being run as the script, name is
assigned the string ‘ main designated it to be main
module.
Recursion is a process in which a function calls itself again and again.
Conditions for implementing Recursion :
i. A recursive function has to contain the following two conditions :
a) A recurrence relation
b) A termination condition
ii. An if condition in the recursive routine which specifies the terminating condition of recursion.
iii. Each time a recursive call is made. A new memory space is allocated to each local variable used by recursive
routing.
iv. During each recursive call to recursive function, the local variable of the recursive function gets a different set of
values but with the same name.

Disadvantages of using Recursion :


i. Uses more storage space because recursive calls along with local variables are stored on the stack.
ii. The computer may run out of memory if the recursive calls are not checked.
iii. It is less efficient in terms of speed and execution time.
Function to find the Factorial of a number using Recursion

Some other programs using Recursion :


a) Recursive program to implement binary search in arrays/list.
b) Function to display Fibonacci Series using Recursion.
c) To calculate the power of an entered number using recursion.
d) Function to calculate the sum of first ‘n’ natural numbers using recursion.
RECURSION vs ITERATION

a) Recursion achieves repetition through a) Iteration explicitly uses a repetition


repeated function calls. function structure.

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.

d) Recursion increases the processor’s d) Iteration decreases the processor’s


operating time. operating time.

e) Defined by the parameter values stored in e) Defined by Control Variable’s value


stack.

e) Recursion decreases the size of code. e) Iterative code is bigger in size.

You might also like