ES102 Introduction To Computing: Lecture 4A Functions
ES102 Introduction To Computing: Lecture 4A Functions
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
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
name_A = list_A[i]
name_B = list_B[i]
list_A[i] = name_B
list_B[i] = name_A
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
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)
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
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
fact = math.factorial(10)
radian = math.radian(90)
sin_theta = math.sin(radian)
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_lyrics(2)
print(Magar yeh toh, depends on ES102)
Example - Parameters and Arguments
Multiple Parameters
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
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,
increment_by_one(x)
increment_by_one(x)
increment_by_one(x+1)
print(x)
x=x+1
increment_by_one(x)
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)
[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,
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,
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
profession = engineer
print_lyrics(profession, 2)
Local and Global Variables Having the Same Name
def funct_1():
x = 3
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
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
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()
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)