Python Functions: Definition & Usage
Python Functions: Definition & Usage
h
Unit 3 Functions
c
Te
.
BDr. Tejaskumar Bhatt
T
Prepared By:
E
F )
S
L &E
G S
(C
Reference:
• Rao, R. N. (2009). Core Python programming (2nd ed.). Dreamtech Press
• Chun, W. (2007). Core Python programming (1st ed.). Pearson.
• Lutz, M. (2013). Learning Python (5th ed.). O'Reilly Media.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
FUNCTIONS
A function is similar to a program that consists of a group of statements that are
intended to perform a specific task.
The main purpose of a function is to perform a specific task or work.
Thus when there are several tasks to be performed, the programmer will write
several functions.
h
There are several ‘built-in’ functions in Python to perform various tasks.
ec
.T
For example, to display output, Python has print() function.
B
Similarly, to calculate square root value, there is sqrt() function and to calculate
E) T
S& FE
power value, there is power() function.
Similar to these functions, a programmer can also create his own functions which
(C LS
are called ‘user-defined’ functions.
G
FUNCTIONS
The following are the advantages of functions:
1. Functions are important in programming because they are used to process data,
make calculations or perform any task which is required in the software
development.
h
ec
avoid code redundancy. It means it is possible to avoid writing the same code
again and again.
.T
B
3. Functions help to make programming modular. A module means a small part of a
E) T
program. Instead of writing one big program, the programmer divides the main
S& FE
task into smaller tasks, called modules.
For each module, the programmer writes a separate function. Later, these
(C LS
functions are called from the main program to complete the whole task. This
G
FUNCTIONS
The following are the advantages of functions:
4. Code maintenance will become easy because of functions. When a new feature has
to be added to the existing software, a new function can be written and integrated
into the software. Similarly, when a particular feature is no more needed by the
user, the corresponding function can be deleted or put into comments.
h
5. When there is an error in the software, the corresponding function can be
ec
modified without disturbing the other functions in the software. Thus code
.T
debugging will become easy.
B
E) T
6. The use of functions in a program will reduce the length of the program.
S& FE
(C LS
G
FUNCTIONS
A function contains a group of statements and performs a specific task.
h
ec
.T
Example:
B
def tejas(): #function name tejas
E) T
print("Hello")
S& FE
(C LS
tejas()
G
h
A function and a method are same except their placement and the way they are
ec
called.
.T
B
class Student: #class name student
E) T
def show(self): #method
print("Hello Student") S& FE
(C LS
s1 = Student()
G
[Link]() # [Link]()
Defining a Function
The define a function using the keyword def followed by function name.
After the function name, we should write parentheses ( ) which may contain
parameters.
h
we can write a function to add two values as: def sum(a, b) :
ec
.T
Here, ‘def’ represents the starting of function definition. ‘sum’ is the name of the
B
function.
E) T
After this name, parentheses ( ) are compulsory as they denote that it is a function
S& FE
and not a variable or something else. In the parentheses, we wrote two variables ‘a’
and ‘b’.
(C LS
These variables are called ‘parameters’. A parameter is a variable that receives
G
data from outside into a function. So, this function can receive two values from
outside and those values are stored in the variables ‘a’ and ‘b’.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Calling a Function
A function cannot run on its own. It runs only when we call it. So, the next step is
to call the function using its name.
While calling the function, we should pass the necessary values to the function
in the parentheses as: sum(10, 15)
Here, we are calling the ‘sum’ function and passing two values 10 and 15 to
that function.
h
ec
When this statement is executed, the Python interpreter jumps to the function
.T
definition and copies the values 10 and 15 into the parameters ‘a’ and ‘b’
B
respectively.
E) T
These values are processed in the function body and result is obtained.
S& FE
The values passed to a function are called ‘arguments’.
(C LS
G
Output:
h
The sum is: 25
ec
The sum is: 12.25
.T
B
Output:
Sum = 25
E) T
Sum = 12.25
S& FE
In the above program, the result is returned by the sum() function through ‘c’ using the
statement: return c
(C LS
When we call the function as: x = sum(10, 15)
G
The result returned by the function comes into the variable ‘x’.
Similarly, when we call the function as: y = sum(1.5, 10.75)
The returned result will come into ‘y
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
h
returned by the function as a tuple.
ec
.T
Output:
B
Result of addition: 15
Result of subtraction: 5
E) T
S& FE
(C LS
G
h
we pass an object (or value) to a function. Also, it is possible to return a function
ec
from another function. This is similar to returning an object (or value) from a
.T
function.
B
The following possibilities are noteworthy:
E) T
S& FE
1. It is possible to assign a function to a variable.
(C LS
2. It is possible to define one function inside another function.
G
Output:
h
Hai Krishna
ec
.T
B
E) T
S& FE
In Program, we have taken a function by the name display() that returns a string.
(C LS
This function is called and the returned string is assigned to a variable ‘x’.
G
h
ec
Output:
.T
Hai How are
B
U?
E) T
S& FE
In Program, we are trying to pass message() function as a parameter or argument
to display() function.
(C LS
Since display() function has to receive another function as its parameter, it should
G
h
ec
Output:
.T
How are U?
B
E) T
S& FE
In Program, we are writing message() function inside display() function.
(C LS
Inside the display() function, when we write: return message
G
The returned message() function can be referenced with a new name ‘fun’.
Task of FUNCTIONS
Defining and Calling Functions (Basics)
1. Write a function to print “Hello World”.
2. Write a function to print your name.
3. Write a function to add two numbers.
4. Write a function to subtract two numbers.
h
5. Write a function to multiply two numbers.
ec
6. Write a function to divide two numbers.
.T
7. Write a function that takes a name as input and prints a greeting message.
B
E) T
8. Write a function that prints the square of a number.
S& FE
9. Write a function that returns the cube of a number.
(C LS
[Link] a function that takes two numbers and returns their average.
G
h
and the datatypes like tuples, lists, and
ec
dictionaries are also objects.
.T
B
If we store a value into a variable as: x = 10
E) T
S& FE
In this case, in other programming languages,
a variable with a name ‘x’ is created and some
(C LS
memory is allocated to the variable. Then the
G
h
that object.
ec
Also, objects are created on heap memory which is a
.T
very huge memory that depends on the RAM of our
B
computer system. Heap memory is available during
E) T
runtime of a program.
S& FE
The location of an object in heap, we can use id()
(C LS
function that gives identity number of an object. For
G
h
computed depending on the
ec
available memory location where
.T
object ‘10’ is stored in the computer.
B
In general, two different objects will
E) T
S& FE
have different identity numbers.
(C LS
When we pass values like numbers,
G
h
function and any modifications to that value will not reflect outside the function.
ec
def modify_value(x):
.T
B
x = x + 10
E) T
S& FE
print("Inside function:", x)
Output
num = 5 Inside function: 15
(C LS
Outside function:
modify_value(num)
G
5
print("Outside function:", num)
h
ec
.T
The value of ‘x’ in the function is 15 and that is not
B
available outside the function.
E) T
This means another object 15 is created in memory
S& FE
and that object is referenced by the name ‘x’.
The reason why another object is created in the
(C LS
memory is that the integer objects are immutable
G
h
print("Inside function:", lst) Inside function: [1, 2, 3, 100]
ec
Outside function: [1, 2, 3,
numbers = [1, 2, 3]
.T
100]
B
modify_list(numbers)
E) T
S& FE
print("Outside function:", numbers)
(C LS
G
h
ec
change their data, the same object gets modified and new object is not created.
.T
B
E) T
S& FE
(C LS
G
But, inside the function, we are creating a new lst = [10, 11, 12] # create a new list (new object)
list as: lst = [10, 11, 12] print("After changing inside function:", lst)
h
and that is referenced by the name ‘lst’. So, numbers = [1, 2, 3, 4]
ec
inside the function, the list is displayed as: [10,
print("Before function call:", numbers)
.T
11, 12]
B
# call the function
But the object that is outside the function is
E) T
change_list(numbers)
S& FE
different. Hence it remains as it is, i.e. [1, 2, 3,
4]. print("After function call:", numbers)
(C LS
Output:
G
Task of FUNCTIONS
Returning Values
1. Write a function to return the area of a rectangle.
2. Write a function to return the perimeter of a circle.
3. Write a function to return both area and perimeter of a square.
4. Write a function that returns both sum and product of two numbers.
h
5. Write a function that returns the maximum of two numbers.
ec
.T
B
E) T
S& FE
(C LS
G
Task of FUNCTIONS
Parameters and Arguments
1. Write a function to return the area of a rectangle.
2. Write a function to return the perimeter of a circle.
3. Write a function to return both area and perimeter of a square.
4. Write a function that returns both sum and product of two numbers.
h
5. Write a function that returns the maximum of two numbers.
ec
6. Write a function to check if a number is even or odd.
.T
7. Write a function to find the factorial of a number.
B
E) T
8. Write a function to find the sum of all elements in a list.
S& FE
9. Write a function to count vowels in a given string.
(C LS
G
Task of FUNCTIONS
Pass by Object Reference
1. Write a function that modifies a list (append element).
2. Write a function that tries to modify an integer (and check if it changes outside).
3. Write a function to clear a list passed as an argument.
4. Write a function that modifies a dictionary inside a function.
h
5. Write a function that demonstrates difference between mutable and immutable
ec
objects.
.T
B
E) T
S& FE
(C LS
G
h
In the following code, ‘a’ and ‘b’ are formal arguments and ‘x’ and ‘y’ are actual
ec
arguments.
.T
B
def sum(a, b): # a, b are formal arguments
E) T
c = a+b
print(c) S& FE
(C LS
# call the function
G
x=10; y=15
sum(x, y) # x, y are actual arguments
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
1. Positional arguments
2. Keyword arguments
3. Default arguments
h
4. Variable length arguments
ec
.T
5. Positional arguments:
B
These are the arguments passed to a function in correct positional order.
E) T
S& FE
Here, the number of arguments and their positions in the function definition
(C LS
should match exactly with the number and position of the argument in the
G
function call.
If we try to pass more than or less than passed arguments, there will be an error.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
h
ec
# call attach() and pass 2 strings
.T
attach('New', 'York') # positional arguments
B
E) T
Output:
S& FE
Total string: NewYork
(C LS
G
If we call the function by passing 3 strings as: attach(‘New’, ‘York’, City’), then
there will be an error displayed.
h
print('Item = %s' % item) Output:
ec
print('Price = %.2f' % price) Item = Sugar
.T
Price = 50.75
# call grocery() and pass 2 arguments
B
Item = Oil
grocery(item='Sugar', price=50.75) # keyword arguments
E) T
Price = 88.00
S& FE
grocery(price=88.00, item='Oil') # keyword arguments
At the time of calling this function, we have to pass two values and we can mention which
(C LS
value is for what.
G
Even though we change the order of the arguments, there will not be any problem as the
parameter names will guide where to store that value.
h
print('Price = %.2f' % price) Output:
ec
# call grocery() and pass arguments Item = Sugar
.T
Price = 50.75
grocery(item='Sugar', price=50.75) # pass 2 arguments
B
Item = Sugar
grocery(item='Sugar') # default value for price is used.
E) T
Price = 40.00
S& FE
At the time of calling this function, if we do not pass ‘price’ value, then the
(C LS
default value is taken. If we mention the ‘price’ value, then that mentioned value
G
is utilized.
So, a default argument is an argument that assumes a default value if a value is
not provided in the function call for that argument.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
h
ec
write: add(a, b)
.T
But, the user who is using this function may want to use this function to find
B
sum of three numbers. In that case, there is a chance that the user may provide 3
E) T
S& FE
arguments to this function as: add(10, 15, 20)
Then the add() function will fail and error will be displayed.
(C LS
G
h
ec
The variable length argument is written with a ‘ * ’ symbol before it in the
.T
function definition as: def add(farg, *args):
B
E) T
Here, ‘farg’ is the formal argument and ‘*args’ represents variable length
S& FE
argument. We can pass 1 or more values to this ‘*args’ and it will store them all in
(C LS
a tuple.
G
h
Output:
ec
sum=0 Formal argument= 5
.T
for i in args: Sum of all
B
sum+=i numbers=
Formal argument= 5
E) T
print('Sum of all numbers= ',(farg+sum))
S& FE
Sum of all
# call add() and pass arguments numbers=
(C LS
15
add(5, 10)
65
add(5, 10, 20, 30)
G
h
ec
Here ‘**kwargs’ is called keyword variable argument. This argument internally
.T
represents a dictionary object.
B
E) T
A dictionary stores data in the form of key and value pairs.
S& FE
It means, when we provide values for ‘**kwargs’, we can pass multiple pairs of
(C LS
values using keywords
G
h
ec
for x, y in [Link](): # items() will give pairs of items
.T
print('key = {}, value = {}'.format(x, y))
B
# pass 1 formal argument and 2 keyword arguments Output:
E) T
Formal argument= 5
display(5, rno=10)
S& FE
key = rno, value = 10
print() Formal argument= 5
(C LS
key = name, value = Tejas
# pass 1 formal argument and 4 keyword arguments key = rno, value = 10
G
h
it is available inside that function. Once we come out of the function, the variable
ec
‘a’ is removed from memory and it is not available.
.T
B
def myfunction(): # local variable in a function
E) T
S& FE
a=1 # this is local var
a+=1 # increment it
(C LS
print(a) # displays 2
G
myfunction()
print(a) # error, not available
h
ec
a=1 # this is global var
.T
def myfunction():
B
b=2 # this is local var
print('a= ', a) # display globalvar
E) T
S& FE
print('b= ', b) # display localvar
(C LS
myfunction()
G
print(a) # available
print(b) # error, not available
h
A Python program to understand global and local variables.
ec
# same name for global and local variables
.T
a=1 # this is global var
B
Output:
def myfunction():
E) T
a= 2
S& FE
a=2 # this is local var a= 1
print('a= ', a) # display local var
(C LS
myfunction()
print('a= ', a) #display global var
G
h
ec
A Python program to access global variable inside a function and modify it.
.T
# accessing the global variable inside a function
B
a=1 # this is global var Output:
E) T
def myfunction(): global a= 1
S& FE
global a # this is global var modified a= 2
global a= 2
print('global a= ', a) # display global var
(C LS
a=2 # modify global var value
G
h
ec
he uses ‘global’ keyword, then he can access only global variable and the local
variable is no more available.
.T
B
The globals() function will solve this problem. This is a built in function which
E) T
returns a table of current global variables in the form of a dictionary.
S& FE
Hence, using this function, we can refer to the global variable ‘a’, as: globals()['a'].
(C LS
Now, this value can be assigned to another variable, say ‘x’ and the programmer
G
h
ec
print('local var a= ', a) localvar a= 2
globalvar a= 1
.T
myfunction()
B
print('global var a= ', a)
E) T
S& FE
(C LS
G
h
ec
= 3 * 2 * 1 * factorial(0)
.T
=3*2*1*1
B
=6
E) T
S& FE
(C LS
G
h
One is supposed to transfer all these disks from pole ‘A’ to another pole, let’s say
ec
‘C’ in minimum number of steps.
.T
While moving these disks from ‘A’ to ‘C’, we can take the help of an intermediate
B
pole ‘B’.
E) T
S& FE
But, the rule is that while moving the disks from one pole to another, we should
(C LS
never place a bigger disk on a smaller disk.
G
For example, to transfer 3 disks from the pole ‘A’ to ‘C’ with the help of an
intermediate pole ‘B’,
h
ec
.T
B
E) T
S& FE
(C LS
G
h
1. Move top n-1 disks from ‘A’ to ‘B’, using ‘C’ as intermediate pole.
ec
2. Move remaining disks, i.e. 1 disk from ‘A’ to ‘C’.
.T
B
3. Move n-1 disks from ‘B’ to ‘C’ using ‘A’ as intermediate pole.
E) T
S& FE
(C LS
G
h
# if more than 1 disk
ec
# move first n-1 disks from A to B using C as intermediate pole
.T
towers(n-1, a, b, c)
B
# move remaining 1 disk from A to C
E) T
print('Move disk %i from pole %s to pole %s'%(n, a, c))
S& FE
# move n-1 disks from B to C using A as intermediate pole
towers(n-1, b, c, a)
(C LS
# call the function
G
h
ec
def square(x):
.T
return x*x
B
The same function can be written as anonymous function as: lambda x: x*x
E) T
S& FE
Observe the keyword ‘lambda’. This represents that an anonymous function is
being created.
(C LS
G
After that, we have written an argument of the function, i.e. ‘x’. Then colon ( : )
represents the beginning of the function that contains an expression x * x. Please
observe that we did not use any name for the function here.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
h
print('Square of 5 = ', value) # display result
ec
.T
B
E) T
S& FE
(C LS
Output:
Square of 5 = 25
G
h
ec
.T
B
E) T
S& FE
(C LS
Output:
Sum = 11.55
G
h
ec
.T
B
E) T
S& FE
(C LS
Output:
Sum = 11.55
G
h
Write a function that validates number of arguments.
ec
Write a function that handles incorrect arguments using try-except.
.T
B
Write a function that uses argument unpacking with * operator.
E) T
Write a function that uses dictionary unpacking with **.
S& FE
(C LS
G
h
Write a function that appends values to a list passed as an argument.
ec
Write a function that tries to change an integer parameter.
.T
B
Write a function to calculate student grade using marks (positional arguments).
E) T
Write a function to print student details (name, roll, marks) using keyword
arguments.
S& FE
(C LS
Write a function to greet multiple names using *args.
Write a function to display student info using **kwargs.
G
Write a function that calculates total marks for variable number of subjects using
*args.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )