0% found this document useful (0 votes)
4 views53 pages

Python Functions: Definition & Usage

Uploaded by

Het Patel
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)
4 views53 pages

Python Functions: Definition & Usage

Uploaded by

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

FET – B.

Tech (CS & E)

Computer Programming Paradigm (Python)


(2601102)

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

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.

2. Once a function is written, it can be reused as and when required. So functions


are also called reusable code. Because of this reusability, the programmer can

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

method is called modular programming, and it makes programming easier,


simpler, and more organized.

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

FUNCTIONS
 A function contains a group of statements and performs a specific task.

 A function can be written individually in a Python program.

 A function is called using its name.

 Function is written outside a class, called directly

h
ec
.T
Example:

B
def tejas(): #function name tejas

E) T
print("Hello")
S& FE
(C LS
tejas()
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Difference between a Function and a Method


 When a function is written inside a class, it becomes a ‘method’.

 A method is called using one of the following ways:


 [Link]()
 [Link]()

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]()

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Returning Results from a Function


 We can return the result or output from the function using a ‘return’ statement in the body of
the function.
 When a function does not return any result, we need not write the return statement in the body
of the function. Now, we will rewrite our sum() function such that it will return the sum value
rather than displaying it.

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)

Returning Multiple Values from a Function


 A function returns a single value in the programming languages like C or Java.
But in Python, a function can return multiple values.
 When a function calculates multiple results and wants to return the results, we
can use the return statement as: return a, b, c
 Here, three values which are in ‘a’, ‘b’, and ‘c’ are returned. These values are

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Functions are First Class Objects


 In Python, functions are considered as first class objects. It means we can use
functions as perfect objects(or value).
 In fact when we create a function, the Python interpreter internally creates an
object.
 Since functions are objects, we can pass a function to another function just like

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

3. It is possible to pass a function as parameter to another function.


4. It is possible that a function can return another function.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Functions are First Class Objects


A Python program to see how to assign a function to a variable.

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Functions are First Class Objects


A Python program to know how to pass a function as parameter to another
function.

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

be defined with another function ‘fun’ as parameter as: def display(fun):

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Functions are First Class Objects


A Python program to know how a function can return another function.

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

 This will return the message() function out of display() function.

 The returned message() function can be referenced with a new name ‘fun’.

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Pass by Object Reference


 In Python, the values are sent to functions by
means of object references.
 We know everything is considered as an object
in Python.
 All numbers are objects, strings are objects,

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

value 10 is stored into the variable ‘x’. We can


imagine ‘x’ as a box where 10 is stored.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Pass by Object Reference


 This is not the case in Python. In Python, everything is
an object. An object can be imagined as a memory block
where we can store some value.
 In this case, an object with the value ‘10’ is created in
memory for which a name ‘x’ is attached.
 So, 10 is the object and ‘x’ is the name or tag given to

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

example, consider the following code snippet:


 x = 10
 id(x)
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Pass by Object Reference


 The preceding lines of code may
display the following output:
1617805016
 This number may change from
computer to computer as it is

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

strings, tuples or lists to a function,


the references of these objects are
passed to the function.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Pass by Object Reference


 In the languages like C and Java, when we pass values to a function, we think
about two ways:
1. Pass by value or call by value
2. Pass by reference or call by reference
 Pass by value represents that a copy of the variable value is passed to the

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)

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Pass by Object Reference


 A Python program to pass an integer to a function and modify it.

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

(not modifiable). So in the function, when we


display ‘x’ value, it will display 15.
 Once we come outside the function and display ‘x’
value, it will display the old object value, i.e. 10.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Pass by Object Reference


Pass by reference represents sending the reference or memory address of the
variable to the function. The variable value is modified by the function through
memory address and hence the modified value will reflect outside the function also.
def modify_list(lst):
[Link](100)
Output:

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Pass by Object Reference


 In Python integers, floats, strings and tuples are immutable. That means their
data cannot be modified.
 When we try to change their value, a new object is created with the modified
value.
 On the other hand, lists and dictionaries are mutable. That means, when we

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Pass by Object Reference


 If we create altogether a new object inside the
def change_list(lst):
function, then it will not be available outside
the function. print("Before changing inside function:", lst)

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

 It means, a new object is created in the function # original list

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

Before function call: [1, 2, 3, 4]


Before changing inside function: [1, 2, 3,
4]
After changing inside function: [10, 11, 12]
Prepared by : Dr. Tejas Bhatt After function
Subjectcall: [1, 2,Programming
: Computer 3, 4] Paradigm (Python )
FET – [Link] (CS & E)

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Formal and Actual Arguments


 When a function is defined, it may have some parameters. These parameters are
useful to receive values from outside of the function. They are called ‘formal
arguments’.
 When we call the function, we should pass data or values to the function. These
values are called ‘actual arguments’.

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)

Formal and Actual Arguments


 The actual arguments used in a function call are of 4 types:

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)

Formal and Actual Arguments


 A Python program to understand the positional arguments of a function.

1. # positional arguments demo


def attach(s1, s2): #to join s1 and s2 and display total string
s3 = s1+s2
print('Total string: '+s3)

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.

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Formal and Actual Arguments


2. Keyword Arguments:
 Keyword arguments are arguments that identify the parameters by their names.

 A Python program to understand the keyword arguments of a function.


# key word arguments demo
def grocery(item, price): """ to display the given arguments """

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.

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Formal and Actual Arguments


3. Default Arguments:
 We can mention some default value for the function parameters in the definition.
 A Python program to understand the use of default arguments in a function.
# default arguments demo
def grocery(item, price=40.00): #to display the given arguments
print('Item = %s' % item)

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)

Formal and Actual Arguments


4. Variable Length Arguments:
 Sometimes, the programmer does not know how many values a function may
receive. In that case, the programmer cannot decide how many arguments to be
given in the function definition.
 For example, if the programmer is writing a function to add two numbers, he can

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Formal and Actual Arguments


4. Variable Length Arguments:
 If the programmer wants to develop a function that can accept ‘n’ arguments, that
is also possible in Python.
 For this purpose, a variable length argument is used in the function definition. A
variable length argument is an argument that can accept any number of values.

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

 A tuple is like a list where a group of elements can be stored

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Formal and Actual Arguments


4. Variable Length Arguments:
 A Python program to show variable length argument and its use.

 # variable length argument demo


def add(farg, *args): # *args can take 0 or more values to add given numbers
print('Formal argument= ', farg)

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Formal and Actual Arguments


4. Variable Length Arguments:
 A keyword variable length argument is an argument that can accept any number
of values provided in the format of keys and values.
 If we want to use a keyword variable length argument, we can declare it with ‘ ** ‘
before the argument as: def display(farg, **kwargs):

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Formal and Actual Arguments


4. Variable Length Arguments:
 A Python program to understand keyword variable argument.
# keyword variable argument demo
def display(farg, **kwargs): # **kwarg can take 0 or more values to display given values
print('Formal argument= ', farg)

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

display(5, rno=10, name='Tejas')

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Local and Global Variables


 When we declare a variable inside a function, it becomes a local variable.
 A local variable is a variable whose scope is limited only to that function where it
is created. That means the local variable value is available only in that function
and not outside of that function.
 In the following example, the variable ‘a’ is declared inside myfunction() and hence

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Local and Global Variables


 See the last statement where we are displaying ‘a’ value outside the function. This
statement raises an error with a message: name ‘a’ is not defined.
 When a variable is declared above a function, it becomes global variable. Such
variables are available to all the functions which are written after it

# global variable example

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

The Global Keyword


 Sometimes, the global variable and the local variable may have the same name.
In that case, the function, by default, refers to the local variable and ignores the
global variable.
 So, the global variable is not accessible inside the function but outside of it, it is
accessible.

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

The Global Keyword


 When the programmer wants to use the global variable inside a function, he can
use the keyword ‘global’ before the variable in the beginning of the function body
as: global a
 global keyword allows a function to use and change a global variable.
 In this way, the global variable is made available to the function and the
programmer can work with it as he wishes.

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

print('modifed a= ', a) # display new value


myfunction()
print('global a= ', a) # display modified value
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

The Global Keyword


 When the global variable name and local variable names are same, the
programmer will face difficulty to differentiate between them inside a function. For
example there is a global variable ‘a’ with some value declared above the function.
 The programmer is writing a local variable with the same name ‘a’ with some
other value inside the function.
 Now, if the programmer wants to work with global variable, how is it possible? If

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

can work with that value.

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

The Global Keyword


# same name for global and local variables
a=1 # this is global var
def myfunction():
a=2 # a is local var
x = globals()['a'] # get global var into x Output:
print('global var a= ', x) globalvar a= 1

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Passing a Group of Elements to a Function


Recursive Functions
 A function that calls itself is known as ‘recursive function’.
 factorial(n) = n * factorial(n-1)
 Ex. factorial of 3 as:
factorial(3) = 3 * factorial(2)
= 3 * 2 * factorial(1)

h
ec
= 3 * 2 * 1 * factorial(0)

.T
=3*2*1*1

B
=6

E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

The Global Keyword


Towers of Hanoi problem through recursion
 Towers of Hanoi is a famous game from ancient China. It is believed that this
game helps to develop intelligence of the children who play it.
 In this game, there will be a group of disks on a pole ‘A’ such that the biggest disk
will be at the bottom and the smaller disks will be on its top.

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

The Global Keyword

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

The Global Keyword


Towers of Hanoi problem through recursion
 These steps can be performed easily by using recursion. Suppose the number of
disks to be moved is ‘n’. If n==1, move that disk from ‘A’ to ‘C’.
 Otherwise, the process of moving ‘n’ disks will be divided into two parts: move the
top n-1 disks and move the remaining 1 disk. The steps are:

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

The Global Keyword


A Python program to solve Towers of Hanoi problem.
# recursive function to solve Towers of Hanoi
def towers(n, a, c, b):
if n==1:
# if only 1 disk, then move it from A to C
print('Move disk %i from pole %s to pole %s' %(n, a, c))
else:

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

n = int(input('Enter number of disks: '))


# we should change n disks from A to C using B as intermediate pole
towers(n, 'A', 'C', 'B')
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Anonymous Functions or Lambdas


 A function without a name is called ‘anonymous function’. So far, the functions
we wrote were defined using the keyword ‘def’.
 But anonymous functions are not defined using ‘def’. They are defined using the
keyword lambda and hence they are also called ‘Lambda functions’.
 lambda argument_list : expression
 The normal function that returns square of a given value.

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)

Anonymous Functions or Lambdas


A Python program to create a lambda function that returns a square value of a
given number.
# a lambda function to calculate square value
f = lambda x: x*x # write lambda function
value = f(5) # call lambda function

h
print('Square of 5 = ', value) # display result

ec
.T
B
E) T
S& FE
(C LS
Output:
Square of 5 = 25
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Anonymous Functions or Lambdas


A lambda function to calculate the sum of two numbers.
# a lambda function to calculate sum of two numbers
f = lambda x, y: x+y # write lambda function
result = f(1.55, 10) # call lambda function
print('Sum = ', result) # display result

h
ec
.T
B
E) T
S& FE
(C LS
Output:
Sum = 11.55
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Anonymous Functions or Lambdas


A lambda function to calculate the sum of two numbers.
# a lambda function to calculate sum of two numbers
f = lambda x, y: x+y # write lambda function
result = f(1.55, 10) # call lambda function
print('Sum = ', result) # display result

h
ec
.T
B
E) T
S& FE
(C LS
Output:
Sum = 11.55
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Task for Function


Practical Argument Examples
 Write a function using only positional arguments.
 Write a function using only keyword arguments.
 Write a function combining positional-only, keyword-only arguments.
 Write a function using type hints for its arguments.
 Write a function with optional arguments.

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

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Task for Function


Practical Argument Examples
 Write an example showing Python’s “pass by object reference”.
 Demonstrate mutation inside a function (list, dict).
 Demonstrate no mutation for immutable types (int, string).
 Modify a list inside a function and show the change outside.
 Modify an integer inside a function and show no change outside.

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 )

You might also like