ES102 Introduction to Computing
Lecture 4A
Functions
Dinesh Garg ([email protected])
&
Jayesh Choudhari ([email protected])
Fall 2017
Acknowledgement
Some of the material in these slides is borrowed from the slides prepared by Prof. Anirban
Dasgupta, Prof. Bireswar Das, Prof. Souradyuti Pal, Prof. Krishna Prasad, Prof. Souman
Chakrabarti (IITB)
What is Function ?
Input Output
function
The idea behind functions is similar to what you know in mathematics
For example, following are legitimate functions in mathematics subject
and so are in python
y = sin(x)
y = exp(x)
Python functions are more general than these in the sense that input
and output can be nearly anything and not just variables
Some Familiar Examples of Functions
Input
Output
function
V1, V2, Vk print() message on terminal
message from terminal input() string
integer or string for integer int() equivalent integer or error
number or string str() equivalent string or error
float number or equivalent string float() equivalent number or error
int or float or string type() data type of the input
int or float number abs() absolute value of the same
float number round() nearest integer
three integers a, b, c range() sequence a, a+c, a+2c,last_num <b
Why we need functions ?
Consider the following piece of code which would swap students in
Friday lab with Thursday lab
for i in range(1, 76, 1):
name_A = list_A[i]
name_B = list_B[i]
list_A[i] = name_B
list_B[i] = name_A
Consider the following alternative piece of the code where we have
abstracted out the swapping part by means of a function call
for i in range(1, 76, 1):
swap(list_A[i], list_B[i])
def statement to define a function
statement_1
Statement_2
statement_3
Colon is important
def function_name(parameters):
statement_t1
This block of code is called body of the function
statement_t2
This block will be executed only when the
Indentation
statement_t3 function is called and not when it is defined
statement_4
This block of the code is not part of the
Statement_5 function definition and is not executed
when the function is called
Example
function definition
def print_lyrics():
print(Papa kehte hain)
print(Beta engineer banega)
Enter
print(My favourite lyrics)
Exit
print_lyrics()
print_lyrics()
print(Magar yeh toh, depends on ES102)
function calls
Function can be called from another function
def print_lyrics():
print(Papa kehte hain)
print(Beta engineer banega)
def my_favourite_song():
print(My favourite lyrics)
print_lyrics()
print(Magar yeh toh, depends on ES102)
my_favourite_song()
We cant call a function before it is defined. But there is a work around and we will come
back to that later!!
What if I do this?
print_lyrics()
def print_lyrics():
print(Papa kehte hain)
print(Beta engineer banega)
print(My favourite lyrics)
print_lyrics()
print(Magar yeh toh, depends on ES102)
We cant call a function before it is defined. But there is a work around and we will come
back to that later!!
Further What if I do this?
def my_favourite_song():
print(My favourite lyrics)
print_lyrics()
print(Magar yeh toh, depends on ES102)
my_favourite_song()
def print_lyrics():
print(Papa kehte hain)
print(Beta engineer banega)
Problem because function definition is not available when the function is being called !!
But What if I make this change ?
def my_favourite_song():
print(My favourite lyrics)
print_lyrics()
print(Magar yeh toh, depends on ES102)
def print_lyrics():
print(Papa kehte hain)
print(Beta engineer banega)
my_favourite_song()
Perfectly Fine !!
Concept of Module
song.py
import lyrics
def my_favourite_song():
print(My favourite lyrics)
lyrics.print_lyrics()
print(Magar yeh toh, depends on ES102)
my_favourite_song()
lyrics.py
def print_lyrics():
print(Papa kehte hain)
print(Beta engineer banega)
Concept of Module
module_1.py module_2.py
import module_2 import module_1
def funct_1(): def funct_1():
statement1 statement1
statement2 statement2
def funct_2(): def funct_2():
statement1 statement1
statement2 statement2
funct_1() funct_1()
funct_2() funct_2()
module_2.funct_1() module_1.funct_1()
module_2.funct_2() module_1.funct_2()
Concept of Module
module_1.py module_2.py
import funct_1 from module_2 import module_1
as funct_3
def funct_1():
def funct_1():
statement1
statement1
statement2
statement2
def funct_2(): def funct_2():
statement1 statement1
statement2 statement2
funct_1()
funct_1()
funct_2()
funct_2()
funct_3()
module_2.funct_2() module_1.funct_1()
module_1.funct_2()
Concept of Module
module_1.py module_2.py module_3.py
import module_2, module_3, module_4
..
..
module_4.py
import() Function and Concept of Module
A modules can be viewed as basket of pre-defined functions (written by
someone else for you) and you can make use of them writing your
code
print(), input(), range(), are called built-in functions and
we can make use of them directly in our code
There are many other modules (e.g. math, random, sys, os)
which needs to be explicitly included in our code before we can make
use of their functions
import(module_1, module_2, module_3) would allow us to use
their in-built functions in our code
math and random Module
import math, random
fact = math.factorial(10)
radian = math.radian(90)
sin_theta = math.sin(radian)
log_x = math.log(x[, base])
exp_x = math.exp(x)
sqrt_x = math.sqrt(x)
random_number = random.choice(range(10))
__name__ variable
Every python script file (i.e. module) has a variable called
__name__ defined automatically whenever that script is either
run from the command prompt directly or called from a different
script file via import command.
If the script file is executed from the command prompt then the
value of the variable __name__ is assigned as __main__
otherwise it is assigned as the name of the script itself
__name__ variable
song.py
__name__ = __main__ import lyrics
def my_favourite_song():
print(My favourite lyrics)
lyrics.print_lyrics()
print(Magar yeh toh, depends on ES102)
my_favourite_song()
lyrics.py
def print_lyrics():
>>> python song.py
print(Papa kehte hain)
print(Beta engineer banega)
__name__ = lyrics
Best Practice - Use of Boiler Plate
my_module.py
import lyrics
def main():
statement_1
statement_2
def funct_1():
statement_1
statement_2
def funct_2():
statement_1
statement_2
if __name__==__main__:
main()
Best Practice - Use of Boiler Plate
lyrics.py
def print_lyrics():
print(Papa kehte hain)
print(Beta engineer banega)
song.py
import lyrics
def my_favourite_song():
print(My favourite lyrics)
lyrics.print_lyrics()
print(Magar yeh toh, depends on ES102)
my_favourite_song()
my_song.py
import lyrics
def main():
my_favourite_song()
def my_favourite_song():
print(My favourite lyrics)
lyrics.print_lyrics()
print(Magar yeh toh, depends on ES102)
if __name__==__main__:
main()
ES102 Introduction to Computing
Lecture 4B
Functions - Parameters, Arguments,
Local and Global Variables
Dinesh Garg ([email protected])
&
Jayesh Choudhari ([email protected])
Fall 2017
Acknowledgement
Some of the material in these slides is borrowed from the slides prepared by Prof. Anirban
Dasgupta, Prof. Bireswar Das, Prof. Souradyuti Pal, Prof. Krishna Prasad, Prof. Souman
Chakrabarti (IITB)
Parameters and Arguments
Parameter
def print_lyrics(repeat):
for i in range(1, repeat):
print(Papa kehte hain)
print(Beta engineer banega)
print(My favourite lyrics) Argument
print_lyrics(2)
print(Magar yeh toh, depends on ES102)
Example - Parameters and Arguments
Multiple Parameters
def print_lyrics(profession, repeat):
for i in range(1, repeat):
print(Papa kehte hain)
print(Beta , profession, banega)
print(My favourite lyrics) Multiple Arguments
print_lyrics(engineer, 2)
print(Magar yeh toh, depends on ES102)
[Note]: The order of the arguments must be the same as the order of the parameters.
Concept of Local and Global Variables
module_1.py module_2.py
Global import module_1
x = 2 GlobalVariable
Variablefor
for
aamodule x = 3
y = Hello module
y = Brother
def funct_1():
def funct_1():
x=3
x=4
print(x =, x) print(x =, x)
def funct_2(): def funct_2():
y=5 y=5
print(y=, y) print(y=, y)
z=10.5 print(x = , x)
print(y = , y)
print(x = , x) LocalVariable for
funct_1()
print(y = , y) a module
funct_2()
funct_1()
module_1.funct_1()
funct_2()
Concept of Local and Global Scopes
module_1.py module_2.py
import module_1
x = 2
Global Scope x = 3
y = Hello
y = Brother
def funct_1():
def funct_1():
x=3 Local Scope x=4
print(x =, x) print(x =, x)
def funct_2(): def funct_2():
y=5 Local Scope y=5
print(y=, y) print(y=, y)
z=10.5 print(x = , x)
print(y = , y)
print(x = , x)
funct_1()
print(y = , y) Global Scope
funct_2()
funct_1()
module_1.funct_1()
funct_2()
Rules for Local and Global Variables
1. A Variable is a
Local Variable if it is defined by an assignment statement within local
scope
Global Variable if it is not a local variable. That is, if it is defined by an
assignment statement within global scope
2.
A. A local variable lives life only until the execution is within that
function block. As soon as execution moves out of a function
block, all the local variables are destroyed. Therefore,
B. A local variable cant be accessed from global scope.
C. However, a global variable can be accessed from a local scope.
But then, global variable cant be modified there. For that use
global keyword
D. Code in a local scope cant access the local variables of some
other local scope
Illustration of Rule 2A
def increment_by_one(num): Local Variable
num = num +1
print(Increased Number is:, num)
x = 2 Global Variable
increment_by_one(x)
increment_by_one(x)
increment_by_one(x+1)
print(x)
x=x+1
increment_by_one(x)
Local variable num is temporary
Example for Rule 2A
def funct_1():
x = 3 Local variable being accessed
from global scope
print(x =, x)
print(x = , x)
Wrong
Example for Rule 2A
song.py
def print_lyrics(profession, repeat):
for i in range(1, repeat):
print(Papa kehte hain)
print(Beta , profession, banega)
print(My favourite lyrics)
print_lyrics(engineer, 2)
print(Magar yeh toh, depends on ES102)
print(profession)
Is this legitimate statement ?
[Answer]: No!!
The variable profession is a local variable to the function and lives a life only when
code is inside the function. That is, it takes birth and dies with code entering and exiting
the function
Local variables cant be access from outside the body of the function but global
variables can be
Rules for Local and Global Variables
1. A Variable is a
Local Variable if it is defined by an assignment statement within local
scope
Global Variable if it is not a local variable. That is, if it is defined by an
assignment statement within global scope
2.
A. A local variable lives life only until the execution is within that
function block. As soon as execution moves out of a function
block, all the local variables are destroyed. Therefore,
B. A local variable cant be accessed from global scope.
C. However, a global variable can be accessed from a local scope.
But then, global variable cant be modified there. For that use
global keyword
D. Code in a local scope cant access the local variables of some
other local scope
Example for Rule 2B
def funct_1():
x = 3
print(y =, y)
def funct_2():
A global variable can be
x = 2 access from local scope
funct_1()
print(x =, x)
y = 3
funct_2()
A Very Important Twist in Example for Rule 2B
def funct_1():
Illegal and will cause the
x = 3
code to break.
print(y =, y)
y = y +1 A global variable can be
def funct_2(): access from local scope but
then it cant be modified
x = 2
funct_1()
print(x =, x)
y = 3
A Very Important Twist in Example for Rule 2B
def funct_1():
x = 3
This will modify the value of
global y the global variable.
print(y =, y)
y = y +1
global keyword before any
def funct_2():
variable within a local scope
x = 2 refers to its global version
funct_1()
print(x =, x)
y = 3
funct_2()
print(y = , y)
Rules for Local and Global Variables
1. A Variable is a
Local Variable if it is defined by an assignment statement within local
scope
Global Variable if it is not a local variable. That is, if it is defined by an
assignment statement within global scope
2.
A. A local variable lives life only until the execution is within that
function block. As soon as execution moves out of a function
block, all the local variables are destroyed. Therefore,
B. A local variable cant be accessed from global scope.
C. However, a global variable can be accessed from a local scope.
But then, global variable cant be modified there. For that use
global keyword
D. Code in a local scope cant access the local variables of some
other local scope
Example for Rule 2C
def funct_1():
x = 3
print(y =, y)
def funct_2(): While in local scope, trying to
x = 2 access variables from other
local scope
y = 3
funct_1()
print(x =, x)
funct_2()
Rules for Local and Global Variables
3. A global variables lives only until the execution of the module is taking
place. After the execution, all global variables are destroyed and hence
when we rerun the same module/script, we dont find old values.
4. A local variable can have the same name as some other
global variable of the same/different module, or
local variable of some other function in the same/different module
5. When execution is inside the body of the function, local variables are
first class citizen and the global variables are the second class citizen.
This means, within function body, python first looks for a local copy of
the variable and if not found then look for the global copy of the
variable having the same name.
Local and Global Variables Having the Same Name
def funct_1():
x = 3
print(x =, x)
def funct_2():
x = 2 local variable takes
precedence if defined locally
funct_1()
print(x = , x)
x = abc
print(x = , x)
funct_2()
Local and Global Variables Having the Same Name
def print_lyrics(profession, repeat):
profession = doctor
for i in range(1, repeat):
print(Papa kehte hain)
print(Beta , profession, banega)
profession = engineer
print_lyrics(profession, 2)
Local and Global Variables Having the Same Name
def funct_1():
x = 3
print(x =, x)
def funct_2(): local variable is not assigned
funct_1() and hence a global variable is
accessed
print(x = , x)
x = abc
print(x = , x)
funct_2()
Local and Global Variables Having the Same Name
def funct_1(x):
print(x =, x)
def funct_2():
When we call a function having
x = 4 parameters then parameters
funct_1(3) become local variables for that
function and get initialised with
print(x = , x) passed arguments
x = abc
print(x = , x)
funct_2()
ES102 Introduction to Computing
Lecture 4B
Functions - return Values and return
Statements
Dinesh Garg ([email protected])
&
Jayesh Choudhari ([email protected])
Fall 2017
Acknowledgement
Some of the material in these slides is borrowed from the slides prepared by Prof. Anirban
Dasgupta, Prof. Bireswar Das, Prof. Souradyuti Pal, Prof. Krishna Prasad, Prof. Souman
Chakrabarti (IITB)
return Statement
statement_1
Statement_2
def function_name(parameters):
statement_t1
statement_t2
statement_t3
return <value or expression>
statement_4
Statement_5
Example
def my_funct(x):
def my_funct(x):
a = x + 1
return x+1
return a
value = my_funct(5)
value = my_funct(5)
print(value = , value)
print(value = , value)
def my_funct(x):
a = x + 1
return a
value = my_funct(my_funct(5) + my_funct(6))
print(value = , value)
Example
import random
def getWeekDay(answerNumber):
if answerNumber == 1:
return 'Monday'
elif answerNumber == 2:
return 'Tuesday'
elif answerNumber == 3:
return Wednesday'
elif answerNumber == 4:
return 'Thursday'
elif answerNumber == 5:
return 'Friday'
elif answerNumber == 6:
return 'Saturday'
elif answerNumber == 7:
return Sunday'
r = random.randint(1, 7)
day = getWeekDay(r)
print(day)
Returning None Value
In python None is a value that denotes absence of any value
Capital N is important here
None is the only value of the NoneType datatype
A function that doesnt contain any return statement, python
automatically adds a return statement with None as the
returning value
For example print() function returns None
ES102 Introduction to Computing
Lecture 4B
Recursion
Dinesh Garg ([email protected])
&
Jayesh Choudhari ([email protected])
Fall 2017
Acknowledgement
Some of the material in these slides is borrowed from the slides prepared by Prof. Anirban
Dasgupta, Prof. Bireswar Das, Prof. Souradyuti Pal, Prof. Krishna Prasad, Prof. Souman
Chakrabarti (IITB)
Example
def main():
n = input(enter a positive integer:)
print(n, != , factorial(n))
def factorial(n): There must be one return statement with our calling
if n == 1: the function. Otherwise it will result in infinite loop.
return 1
else:
return n* factorial(n-1)
if __name__==__main__:
main() Function is calling itself repeatedly.
Example
def main():
n = input(enter a positive integer:)
print(n, != , factorial(n))
def factorial(n):
if n == 1:
return 1
else:
return n* factorial(n-1)
if __name__==__main__:
main()
factorial (n) factorial (n-1) factorial (n-2) factorial (1)
Example - Print the last element of Fibonacci Series
def main():
n = input(enter a positive integer:)
print(The last element is fibonacci(n))
def fibonacci(n):
if n <= 2:
return 1
else:
return (fibonacci(n-1) + fibonacci(n-2))
if __name__==__main__:
main()
Example - Print the last element of Fibonacci Series
def main():
n = input(enter a positive integer:)
print(The last element is fibonacci(n))
def fibonacci(n):
if n <= 2:
return 1
else:
return (fibonacci(n-1) + fibonacci(n-2))
if __name__==__main__:
main()
factorial (n)
factorial (n-1) factorial (n-2)
factorial (n-2) factorial (n-3) factorial (n-3) factorial (n-4)
Recursion
Recursion is a technique that breaks the problem into one or
more sub-problems that are similar to the original problem
but of a smaller size.
Types of recursions
Linear v/s Tree
Direct v/s Indirect
Tail v/s Head