0% found this document useful (0 votes)
8 views10 pages

Ch 02 Functions 02

The document provides an overview of user-defined functions in Python, explaining their purpose, structure, and significance in programming. It details how to define and call functions, the importance of indentation, and various types of arguments including positional, default, and keyword arguments. Additionally, it includes several example programs demonstrating function creation, calling, and returning values.
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)
8 views10 pages

Ch 02 Functions 02

The document provides an overview of user-defined functions in Python, explaining their purpose, structure, and significance in programming. It details how to define and call functions, the importance of indentation, and various types of arguments including positional, default, and keyword arguments. Additionally, it includes several example programs demonstrating function creation, calling, and returning values.
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/ 10

25-06-2024

User – Defined Functions :


A function is a subprogram or a part of a
program that performs a specific task. In other
Chapter : 02 words we can say that a function is a common
structuring element that allows us to use a

Functions piece of code repeatedly in different parts of a


program.
The use of functions improves a
program’s clarity and readability and makes
programming more efficient by reducing code
duplication and breaking down complex tasks
into more manageable pieces. Functions are
also known as routines, sub – routines,
1 methods, procedures or sub – programs. 2

How to define and call a function in Python : NOTE :


A user – defined Python function is Statements below “def” begin with four
created or defined by the ‘def’ keyword spaces. This is called “Indentation”. It is a
followed by the function name and parenthses requirement of Python that the code following a
( ) as shown below : colon must be indented.
Syntax : A function definition consists following
components :
(1.) Keyword “def” marks the start of function
def function_name(comma separated parameters):
header.
“ “ “ docstring ” ” ” (2.) A function name to uniquely identify it.
Keyword Function Function naming follows the same rules as rules
Definition of writing identifiers in Python.
statements (3.) Parameters (arguments) through which we
pass values to a function. They are optional.
3 4

(4.) A colon ( : ) to mark the end of function PROGRAM – 1 :


header. >>> def func1( ) :
(5.) Optional documentation string (docstring) to print ( “I am Learning Functions in Python.”)
describe what the function does. The above code is called the “function body”.
(6.) One or more valid Python statements that
make up the function body. Statements must have
>>> func1( ) # Function Call
same indentation level ( usually 4 spaces).
I am Learning Functions in Python. #OUTPUT
(7.) An optional “return” statement to return a
value from the function.
PROGRAM : 1  Let us define a simple function NOTE : The above program displays a message
(which does not return any value) by using the on the screen and does not contain a “return”
command “def func1( ) :” and call the function. statement. The functions that return no value are
The output of the function will be : “I am Learning called “void Functions”.
Functions in Python.”
5 6

1
25-06-2024

NOTE : “void functions” may display something Python follows a particular style of
on the screen or have some other effect, but they indentation to define the code. Since, Python
don’t have a return value. If we try to assign the functions don’t have any explicit beginning or
result of such a function to a variable, we get a end, like curly braces to indicate the start and
special value called “None”. stop for the function, they have to rely on this
NOTE : A Python function can be called directly indentation.
from the “Python shell”.
NOTE : User – Defined functions (UDFs) in Python PROGRAM – 2 :
are called or invoked by using only the function >>> def func1( ) :
name. print ( “I am Learning Functions in Python.”)
Significance of Indentation (Spaces) in Python:
Indentation rules to declare Python When we write “print( )” function right below the
functions are applicable to other elements of “def func1( )”, it will show an “Indentation Error :
Python as well like declaring conditions, loops or expected an indented block”.
variable. 7 8

NOTE : ( 1. ) The above error can be removed by OUTPUT :


making proper indentation before the print( ) I am learning Functions in Python
function. At least one indent is enough to make Still in function
our code work successfully.
PROGRAM – 4 : Write a Python function to accept
( 2. ) Apart from this, it is also necessary that while the radius of a circle and print its area.
giving indentation, we maintain the same indent
def cir_area( ) :
for the rest of our code.
“ “ “ This function accepts the radius of the circle
(3.) When we apply same indentation for both the
and calculates the area of the circle.
statements and align them in the same line, it
gives the expected output. Input Parameter : radius
Return value : None ” ” ” # docstring
PROGRAM – 3 :
r = float(input(“Enter the radius of the circle : ”)
>>> def func1( ) :
ar = 3.14 * r * r
print ( “I am Learning Functions in Python.”)
print (“The area of the circle : ” , ar)
print (“Still in Function”)
9 10

How Function Returns a Value : def arearectangle(length , breadth) :


Usually, function definition have the “ “ “ This function accepts the length and breadth
following basic structure : of a rectangle as arguments , calculate the Area of
def function_name(arguments): the rectangle and returns the area
statements Input Parameter : None
return <value> Arguments : length and breadth of rectangle
‘return’ command in Python specifies what value Return value : area of the rectangle ” ” ” # docstring
is to be returned back to the calling function. area = length * breadth
Function can take input values as parameters, return area
execute them and return output (if required) to the
calling function with a return statement.
NOTE: In interactive mode we can call the above
function as follows :
PROGRAM – 5 : Write a Python function to >>> arearectangle(30 , 20)
compute area of a rectangle. 11
OUTPUT : 600 12

2
25-06-2024

PROGRAM – 6 : Write a Python function to find OUTPUT :


factorial value of a given number. The function The factorial of 1 1
should return the calculated factorial value using The factorial of 2 2
return statement.
The factorial of 3 6
# Function for calculating factorial value of a
The factorial of 4 24
# number using return statement
def factorial(num):
Function returning multiple values :
fact = 1
Unlike other high – level languages like C, C++,
while num >= 1 : Java etc, wherein a function can return only one
fact = fact * num value, a function in Python can return multiple
num = num – 1 values. Thus, a return statement in Python
return fact function can return any number of values.
for I in range(1,5) :
print (“The factorial of ”, i , factorial(i)) 13 14

PROGRAM – 7 : Write a Python PROGRAM to ADD NOTE: In the above program , we have used a
and SUBTRACT two values and to return them. single return statement to return the two values at
the same time.
# Program to illustrate return statement returning
# multiple values. PROGRAM – 8 : Write a Python PROGRAM to
perform all the four basic operations and to return
them.
def add_diff (x , y) :
# Program to calculate Addition , Subtraction,
add = x + y
# Multiplication & Division and return those values.
diff = x – y
def calc(a , b) :
return add , diff
add = a + b
a , b = add_diff (200 , 100)
sub = a – b
print(“The sum of two numbers is : ”, a)
multi = a * b
print(“The diiferences of two numbers is : ”, b)
15 div = a / b 16

return add , sub , multi , div NOTE: A function may or may not return a value. In
nutshell, while creating functions, we can use two
result = calc ( 500 , 40) keywords:
print (“ The results obtained are : ”) 1. ‘def’ (mandatory)
for i in result : 2. ‘return’ (optional)
print ( i )
PROGRAM – 9 : Write a Python program to
implement calculator functions using the concept
OUTPUT :
of modules. (Alternative method of program – 8).
The results obtained are :
540
We will first create a module named ‘calculate.py’
460 as per the code given below. Then we shall call this
20000 module through Python shell prompt.
12.5 17 18

3
25-06-2024

PROGRAM – 9 : OUTPUT :
# Program to implement “calculate” module >>> import calculate #invoking ‘calculate’ module
>>> calculate.add(5 , 20)
def add(a , b): 25
return a+b >>> calculate.diff(5 , 20)
def diff(a , b) : –15
return a – b >>> calculate.mult(5 , 20)
def mult(a , b) : 100
return a * b >>> calculate.div(5 , 20)
def div(a , b) : 0.25
return a / b >>> calculate.rem(5 , 20)
def rem(a , b) : 0
return a // b 19 20

NOTE: Parameters and Arguments in Functions:


(1.) A return statement returns a value from a Parameters : The values or variables that appear in
function. ‘return’ without an expression argument the function header are called “Parameter” or
is used to return from the middle of a function in “Formal Parameters” or “Formal Argument”. These
which case the ‘None’ value is returned. are the values required by a function to work.
(2.) A function must be defined before it is If there are more than one value required by
called. Statements inside the functions are not the function to work upon, then all of them will be
executed until the function is called. The order in listed in parameter list separated by comma.
which statements are executed is called the flow of
execution. Statements are executed one at a time, Argument : An Argument is a value that is passed
in order, until a function call is reached. to the function when it is called. The values or
(3.) ‘return’ statement returns the value of an variables that appear in the function call statement
expression following the return keyword. In the are called “Argument” or “Actual Arguments” or
absence of the return statement, the default value “Actual Parameters”
‘None’ is returned. 21 22

NOTE : (5.) In Python functions, if we are passing values of


(1.) List of arguments should be supplied in the immutable types , i.e. numbers, strings etc. to the
same order as the parameters are listed. called function, then the called function cannot
(2.) Bounding of parameters to arguments is done alter their values. But in case parameters passed
in 1 : 1. So, the number and type of arguments are mutable in nature, such as lists or dictionaries,
should be same as mentioned in parameter list. then called function would be able to make
changes to them.
(3.) Arguments in Python can be one of these value
types : literals or variables or expressions, (6.) The user can set arguments to default values in
whereas parameters have to be some names, i.e. function definitions. For Ex. :
variables to hold incoming values ; parameters >>> def f1(x , a = 1)
cannot be literals or expressions. return a * x ** 2
(4.) The alternative names for argument are “Actual If this function is called with only one argument,
Parameter” or “Actual Argument”. The alternative the default value of 1 is assumed for the second
names for parameters are “Formal Parameters” or argument.
“Formal Arguments”. 23 24

4
25-06-2024

However, the user is free to change the second Here, ‘x’ & ‘y’ are formal arguments whereas 20 &
argument from its default value : For Ex. : 30 are actual arguments.
>>> f1(2 , a=2) # f1(2,2) would also work. On the basis of above example, four types of
If there is a function with many parameters and we “Actual Arguments” are allowed in Python :
want to specify only some of them in function call, (a.) Positional Arguments.
then value for such parameters can be provided by (b.) Default Arguments
using their name, instead of the position (order). (c.) Keyword Arguments
This is called “Keyword Argument”.
(d.) Variable Length Arguments
Types of Arguments :
Consider the following example :
(a.) Positional Arguments :
def f1( x , y ) :
Positional arguments are arguments passed
------------------ to a function in correct positional order.
------------------ FOR EX. :
f1(20,30) 25 26

# To demonstrate Positional Arguments (b.) Default Arguments :


def subtract (a,b) : Sometimes we can provide default values for
print ( a – b ) the positional arguments.
OUTPUT : FOR EX. :
(1.) >>> subtract(200,100) def add(a=10 , b=20) :
100 return a+b
(2.) >>> subtract(100,200) add( ) # Valid
–100 add(20) #Valid
NOTE : add(50,100) #Valid
(1.) The number and position of arguments must be OUTPUT :
matched. If we change their order, then the result (1.) 30
will be changed. (2.) 40
(2.) If we change the number of arguments passed, (3.) 150
then it shall result in an error. 27 28

NOTE : (2.) add(x,y) # Valid


(1.) If we are not passing any variable or value, then (3.) add(100,200) # Valid
only default values will be considered. (4.) add(x, y=500) #Valid
(2.) Default argumented functions are useful in (5.) add(x= 100,y) #Valid
reducing the number of functions in a program. But, >>> def add(a=10,b) : #Invalid
(3.) We must remember that if we are passing return a+b
default arguments to a function, then we should
(C.) Keyword Arguments :
not take non – default arguments, otherwise it will
result in an error. For Ex. : If there is a function with many parameters
and we want to specify only some of them in
>>> def add(a=10, b=20) : #Valid
function call, then value for such parameters can
return a+b be provided by using their ‘name’ instead of the
The above function can be called by the following position (order). These are called “Keyword
methods : arguments”.
(1.) add( ) # Valid 29 30

5
25-06-2024

Thus, using keyword arguments, we can pass NOTE :


argument value by keyword, i.e. by parameter (1.) Here, the order of arguments is not important but
name. For Ex. : the number of arguments must be matched.
>>> def add(a,b) : (2.) We can use both positional and keyword arguments
return a+b simultaneously. But first we have to take positional
argument and then the keyword argument, otherwise it
The above function can be called by the following will generate a syntax error.
methods :
For Ex. :
(1.) add(a=50 , b=90) # Valid >>> def add(a,b) :
(2.) add(b=80 , a=100) # Valid return a+b
The above function can be called by the following
OUTPUT : methods :
(1.) 140 (1.) add(a=50 , b=90) # Valid
(2.) 180 (2.) add(b=80 , a=100) # Valid
31 (3.) add(a=500, 100) #Invalid 32

Advantages of writing functions with keyword (2.) >>> fun(3 , 7 , 10)


arguments are : OUTPUT : a is 3 b is 7 c is 10
(1.) Using the function is easier as we do not need to (3.) >>> fun(25 , c = 20)
remember the order of the arguments. OUTPUT : a is 25 b is 1 c is 20
(2.) We can specify values of only those parameters (4.) >>> fun(c = 20 , a = 10)
which we want to, as other parameters have default
argument values. OUTPUT : a is 10 b is 1 c is 20
Ex. 1 : Consider the following function definition : NOTE :
def fun(a , b = 1 , c = 5) : (1.) 1st and 2nd call to function is based on default
argument value, and the 3rd and 4th call are using
print (“ a is : ”, a , “ b is : ”, b , “ c is : ”, c)
“Keyword Argument”.
The above function can be called by the following
(2.) The function named fun( ) has three parameters out
methods :
of which the first one is without default value and the
(1.) >>> fun(3) other two have default values. So, any call to the
OUTPUT : a is 3 b is 1 c is 5 function should have at least one argument.
33 34

While using keyword arguments, the following points (8.) We cannot have a parameter on the left with default
should be kept in mind : argument value without assigning default values to
(1.) An argument list must have any positional parameters lying on its right side.
arguments followed by any keyword arguments.
(2.) Keywords in argument list should be from the list of (d.) Variable Length Arguments :
parameters name only. As the name suggests, in certain situations, we
(3.) No parameter should receive value more than once. can pass variable number of arguments to a function.
(4.) Parameter names corresponding to positional Such type of arguments are called variable length
arguments cannot be used as keywords in the same arguments.
calls. Variable length arguments are declared with * (asterisk)
(5.) The default value assigned to the parameter should symbol in Python as follows :
be a constant only. >>> def fun1( *n ) :
(6.) Only those parameters which are at the end of the We can call this function by passing any number of
list can be given default value. arguments, including zero number. Internally, all these
(7.) The default value is evaluated only once at the point values are represented in the form of a tuple.
35 36
of function definition.

6
25-06-2024

For Ex. : NOTE :


>>> def sum( *n ) : Anything calculated or changed inside a function but
total = 0 not specified as an output quantity (either with or
for i in n : global) will be deleted once the function stops running.
total = total + I For Ex. :
>>> def fun1(x , y):
print ( “ The sum is = ” , total )
a=x+y
The above function can be called by the following b=x–y
methods : return a**2 , b**2
( 1.) sum( ) Function Call :
( 2.) sum(20) >>> fun1(3 , 2)
( 3.) sum(20,30) ( 25 , 1 )
( 4.) sum(10, 20, 30) If we try to call a or b, we get an error message :
( 5.) sum(10, 20, 30, 40,50) >>> a # will give an error
37 38

Passing Arrays / Lists to a Function : For Ex. :


Arrays in Python are actually lists that contain mixed def list_prnt(l):
data – types. However, the ‘numarray’ module contains
support for true arrays. Therefore, for proper print("The passed list is : ")
implementation of arrays, we require ‘Numpy library / print (l)
interface’. We shall be implementing lists as arrays
using Python shell.
However, lists are better than arrays as they may hold
a = [1,2,3,4]
elements of several data – types, whereas in case of list_prnt(a)
arrays, the elements should be of same data – type only
and, hence, lists are much more flexible and faster than
OUTPUT :
arrays.
NOTE : A list can be passed as argument to a function The passed list is :
similar to passing normal variables as arguments to a [1, 2, 3, 4]
function.
39 40

Scope of Variables : (2.) Local Scope (Function Scope) :


Scope of variables refers to the part of a program  Names assigned inside a function definition or
where it is visible, i.e. area where we can refer or loop.
use that variable. In other words, we can say that
scope holds the current set of variables and their For Ex. :
values.
There are two types of scopes in Python :
>>> a = 2 # ‘a’ is assigned in the interpreter, so it’s global
(1.) Global Scope (Module Scope)
>>> def f(x) : # ‘x’ is in the function’s argument list, so it’s local
(2.) Local Scope (Function Scope)
y=x+a # ‘y’ is only assigned inside the function, so it’s local
return y # using the same local variable
(1.) Global Scope (Module Scope) :
 Names assigned at the top level of a module, or
directly in the interpreter.
 Names declared global in a function. 41 42

7
25-06-2024

NOTE : NOTE :
(1.) We can use the same names in different scopes. (2.) Changing a global name used in a function
For Ex. : definition changes the function.
>>> a = 2 For Ex. :
>>> def f2(x , y): >>> a = 2
a=x+y >>> def f( x ) :
b=x–y return x + a # this function is , effectively, f(x)=x+2

return a**2 , b**2


>>> f( 4 ) # Function call with x = 4
OUTPUT :
>>> 6 # OUTPUT
>>> a
>>> a = 1 # The value of GLOBAL variable a = 1 now.
2
>>> f( 4 ) # since we set a=1, f(x) = x+1 now.
The local ‘a’ is deleted as soon as the function stops >>> 5 # OUTPUT
running.
43 44

NOTE : It can also make our program easier for non – Python
(3.) Unlike some other languages, Python function programmers to read.
arguments are not modified by default. For Ex. :
For Ex. : def hello( ):
>>> x = 4 print (“Hello , World”)
def main( ) :
>>> f (x)
print (“ This is the main( ) function.”)
5
hello( )
>>> x
Function Call :
4
>>> main( )
Using main() as a function :
Including a main() function is not mandatory in Python. It
OUTPUT :
can structure our Python programs in a logical way that
puts the most important components of the program into This is the main( ) function.
one function. 45
Hello , World 46

NOTE : RECURSION :
It is remembered that a function does not execute until it Recursion is one of the most powerful tools in a
is invoked, whether it is main( ) or any other user – programming language. Recursion is the property of a
defined function. function to call itself again and again and such types of
Flow of execution of program containing Function Call : function is called “Recursive Function”.
Execution always begins at the first statement of the
program. Statements are executed one at a time, starting Disadvantages of using Recursion :
from the top to bottom. Function definition does not alter (1.) It consumes more storage space because the
the flow of execution of a program, as the statements recursive calls along with local variables are stored on
inside the function is not executed until the function is the stack.
called. (2.) The computer may run out of memory if the
On a function call, instead of going to the next statement recursive calls are not checked.
of the program, the control jumps to the body of the (3.) It is less efficient in terms of speed and execution
function, executes all statements of the function, time.
starting from the top to the bottom and then comes back
to the point where it left off. 47 48

8
25-06-2024

How Recursion Works : # Python program to calculate power of an inputted


Recursion is implemented by dividing the recursive # number using RECURSION.
problem into two parts. A useful recursive function
usually consists of the following parts : def power( x , n ) :
 Terminating Part ( for the smallest possible if n = = 0 :
problem) when the function returns a value
return 1
directly.
else :
 Recursive part which contains one of the more
recursive calls on smaller parts of the problem. return x * power( x , n – 1 )

PROGRAM : 1 a=2
Write a Python program using recursive function to print ( power ( a , 4 ))
implement the power( ) function.
49 OUTPUT : 16 50

PROGRAM : 2 if num < 0 :


Write a Python function to calculate the sum of first print (“ Enter a positive number : ”)
‘n’ natural numbers using recursion. else :
# Function to find the sum of first ‘n’ Natural print (“ The sum is = ”, recur_sum(num))
# Numbers using Recursion. OUTPUT :
def recur_sum( n ) : Enter a Number : 6
if n <= 1 : The sum is = 21
return n
else : PROGRAM : 3
return n + recur_sum( n – 1 ) Write a Python function to display the FIBONACCI
series using RECURSION
num = int ( input ( “ Enter a Number : ” ) ) # Function to display the FIBONACCI series using
51
# RECURSION 52

def recur_fibo(n) : PROGRAM : 4


if n <= 1: Write a Recursive function to calculate the Factorial
return n of a number.
else: # Function to find the Factorial of a Number using
return (recur_fico(n–1)+recur_fibo(n–2)) # Recursion
terms = int(input(“ How many terms you want to print:”)) def recur_factorial( n) ;
print(“ The FIBONACCI series generated is : ”) if n == 1:
for i in range(terms): return n
print(recur_fibo(i)) else:
OUTPUT : return n * recur_factorial( n – 1 )
How many terms you want to print : 9
The FIBONACCI series generated is : num = int(input(“ Enter a Number : ”)
0 1 1 2 3 5 8 13 21 53 54

9
25-06-2024

if num < 0: NOTE :


print(“Factorial of a negative number does not exist: ”) (1.) In Binary search technique, the entire sequence
elif num == 0: of numbers (list/array)is divided into two parts and
print (“ The factorial of 0 is 1.”) the middle element of list/array is extracted. This
technique is also known as “Divide and Conquer
else:
Technique”.
print(“The factorial of”, num,“is”, recur_factorial(num))
(2.) Binary search works only on sorted arrays i.e.
OUTPUT : either in ascending order or descending order.
Enter a Number : 10 (3.) Binary search is more powerful than “Linear
The factorial of 10 is 3628800 search” since the array/list is divided into two
halves at each stage.
PROGRAM : 5 (Binary search in lists/arrays)
(4.) Less than 20 comparisions are required to
Write a Recursive program to implement Binary
search an element of in an array/list of one lakh
search in lists / arrays. elements.
55 56

# Program for Binary Search in a List/Array using List = [ 5, 11, 22, 36, 99, 101 ]
# Recursion print (bin_search (list, 0, 5, 36))
def bin_search(list, low, high, val) :
print (bin_search (list, 0, 5, 100))
if high < low :
return None
else: OUTPUT :
midval = low + (( high – low ) // 2) 3
# Compare the search item with middle most value None
if list[midval] > val:
return bin_search( list, low, midval–1, val)
elif list[midval] < val :
return bin_search( list, midval+1, high, val)
else :
return midval 57 58

59

10

You might also like