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 4
…
⋮
Function definitions
def function_k(..,..):
are “digested” for
…
future use
statement_1
statement_2
Actual computation
⋮
starts from
statement_n statement_1
Control flow
Need to vary computation steps as values change
Conditional execution
Function definitions
Conditional execution
if m%n != 0:
(m,n) = (n,m%n)
Second statement is executed only if the condition
m%n != 0 is True
if condition:
statement_1 # Execute conditionally
statement_2 # Execute conditionally
statement_3 # Execute unconditionally
Alternative execution
if m%n != 0:
(m,n) = (n,m%n)
else:
gcd = n
else: is optional
Shortcuts for conditions
Numeric value 0 is treated as False
if m%n:
(m,n) = (n,m%n)
else:
gcd = n
Multiway branching, elif:
if x == 1:
if x == 1:
y = f1(x)
y = f1(x)
else:
elif x == 2:
if x == 2:
y = f2(x)
y = f2(x)
elif x == 3:
else:
y = f3(x)
if x == 3:
else:
y = f3(x)
y = f4(x)
else:
y = f4(x)
Loops: repeated actions
for i in [1,2,3,4]:
y = y*i
z = z+1
for i in [1,2,..,n]:
. . .
def factors(n):
flist = []
for i in range(1,n+1):
if n%i == 0:
flist = flist + [i]
return(flist)
Loop based on a condition
Often we don’t know number of repetitions in
advance
while condition:
. . .
def gcd(m,n):
if m < n:
(m,n) = (n,m)
while m%n != 0:
(m,n) = (n,m%n)
return(n)
Summary
Normally, statements are executed top to bottom,
in sequence