Nptel Mooc: Programming, Data Structures and Algorithms in Python
Nptel Mooc: Programming, Data Structures and Algorithms in Python
PROGRAMMING,
DATA STRUCTURES AND
ALGORITHMS IN PYTHON
Week 2, Lecture 5
…
⋮
Function definitions
def function_k(..,..):
are “digested” for
…
future use
statement_1
statement_2
Actual computation
⋮
starts from
statement_n statement_1
Function definition
def f(a,b,c):
statement_1
statement_2
..
return(v)
..
Body is indented
def stupid(x):
n = 17
return(x)
n = 7
v = stupid(28)
# What is n now?
n is still 7
Name n inside function is separate from n outside
Defining functions
A function must be defined before it is invoked
This is OK
This is not
def factorial(n):
if n <= 0:
return(1)
else:
val = n * factorial(n-1)
return(val)
Summary
Functions are a good way to organise code in logical
chunks