Module 3 - Program Control Flow
Module 3 - Program Control Flow
BOOLEAN VALUES
Boolean: Example:
Boolean data type have two values. >>> 3==5
False
They are 0 and 1.
>>> 6==6
0 represents False True
1 represents True >>> True+True
2
True and False are keyword >>> False+True
1
>>> False*True
0
CONDITIONAL STATEMENTS
A program’s control flow is the order in which the program’s code executes.
The control flow of a Python program is regulated by conditional statements,
loops, and function calls.
This section covers the if statement and for and while loop
Conditional statements
if statement
if... Else statement
if...elif...else statement
Nested if....else statement
IF STATEMENT
If statement Syntax :
if statement is used for branching when if condition :
a single condition is to be checked. statements
Statements
The condition enclosed in if statement
decides the sequence of execution of
instruction.
If the condition is true, the statements
inside if statement are executed,
otherwise they are skipped.
IF STATEMENT
Program to provide flat rs 500, if the purchase Determine whether a person is eligible to vote
amount is greater than 2000 Age =int(input(“Age?”))
purchase=eval(input(“enter your purchase If age >=18:
amount”))
if(purchase>=2000): Print(“He /She is eligible to cast the vote”)
purchase=purchase-500 Print(“ not Eligible “)
print(“amount to pay”,purchase)
IF STATEMENT
Write a Python script to input 3 coefficients of a quadratic equation (ax2+bx+c=0) and calculate the
discriminant
a=float(input('Coefficient of x^2? '))
b=float(input('Coefficient of x ? '))
c=float(input('Constant Term ? '))
d=b*b-4*a*c #b**2-4*a*c
if d==0:
x=-b/(2*a)
print('Real and Equal Roots’)
print(x, x)
if d>0:
x1, x2=(-b+d**0.5)/(2*a), (-b-d**0.5)/(2*a)
print('Real and Distinct Roots’)
print(x1, x2)
if d<0:
x1, x2=(-b+d**0.5)/(2*a), (-b-d**0.5)/(2*a)
print('Complex Roots’)
print(x1, x2)
IF-ELSE STATEMENT
Syntax for if-else:
if-else statement if condition:
statement1
statement2
In the alternative the condition must be true or false. In
else:
this else statement can be combined with if statement. statement1
The else statement contains the block of code that statement2
executes when the condition is false.
If the condition is true statements inside the if get
executed otherwise else part gets executed.
The alternatives are called branches, because they are
branches in the flow of execution.
IF-ELSE STATEMENT
if-elif-else
Syntax:
The elif is short for else if.
if expression:
This is used to check more than one condition.
statement(s)
If the condition1 is False, it checks the condition2 of the elif
elif expression:
block.
If all the conditions are False, then the else part is executed.
statement(s)
elif expression:
Among the several if...elif...else part, only one part is
executed according to the condition.
statement(s)
The if block can have only one else block. But it can have ...
multiple elif blocks. else:
The way to express a computation like that is a chained statement(s)
conditional.
IF-ELIF-ELSE
student mark system Positive or negative
mark=eval(input("mark: or zero
")) num=float(input('Enter
if(mark>=90): a value? '))
print("grade:S") if num>0:
elif(mark>=80): print('Positive')
print("grade:A") elif num<0:
elif(mark>=70): print('Negative')
print("grade:B") else:
elif(mark>=50): print('Zero')
print("grade:C")
else:
print("fail")
IF-ELIF-ELSE
While
For
Break
Continue
pass
WHILE LOOP
while loop
Python scripts are given below to display numbers 1, 2, 3 4 and 5 on the
screen
k=1 k=1 k=1
print(k) print(k); k+=1 while k<=4:
print(k+1) print(k); k+=1 print(k)
print(k+2) print(k); k+=1 k+=1 #OR,
print(k+3) print(k); k+=1 k=k+1
print(k+4) print(k);
WHILE LOOP
i=0
Write a Python script to generate While i<10:
and display following sequence on if I ==5:
screen: 2, 4, 6, 8, ..., 20
break
k=2
while k<=20: Print(I, end=“ “)
print(k)
k+=2
RANGE()
range()
Function range() generates a list of numbers, which is generally used to iterate over
with for loop. Often you will want to use this when you want to perform an action for
fixed number of times.
Function range() has three syntaxes.
1. range(StopVal): generates sequence of integers 0, 1, 2, 3, ..., StopVal-1
Start value of the sequence is always 0 (zero) when range() function has single
parameter.
range(6) will generate sequence of integers 0, 1, 2, 3, 4, 5
range(11) will generate integers 0, 1, 2, 3, ..., 9, 10
range(0) or range(-5) does not generate an any sequence because 0>StopVal
RANGE()
2. range(StartVal, StopVal): generates integers StartVal, StartVal +1, StartVal +2, , ...,
StopVal-1
range(1, 6) will generate sequence of integers 1, 2, 3, 4, 5
range(6, 11) will generate sequence of integers 6, 7, 8, 9, 10
range(-3, 4) will generate sequence of integers -3, -2, -1, 0, 1, 2, 3
range(3, 0) or range(3, -4) does not generate an any sequence of integer because
StartVal>StopVal
RANGE()
Nested loop
Till now we have learned how to use single while / for loop. The role of a loop is too repeat a
block (group of Python statements) or a single Python statement for a specific number of
times.
A block inside a loop usually contained either a print() function or a assignment statement or
a if statement or a combination of print(), assignment and if statements.
But now we will learn that a block or statement inside a loop may contain another loop – this
is known as nested loop (one loop contains at least one more loop).
General
rule for nested loop is given below:
NESTED LOOP
#using nested while loop #using nested for loop
nor=int(input('Rows? ')) nor=int(input('Rows? '))
noc=int(input('Cols? ')) noc=int(input('Cols? '))
ch=input('Fill Char? ') ch=input('Fill Char? ')
k=1 for k in range(1, nor+1):
while k<=nor: for j in range(1, noc+1):
j=1 print(ch, end=‘’)
while j<=noc: print()
print(ch, end=‘’)
j+=1
print()
k+=1
#using nested while loop #using nested for loop
n=int(input('Rows? '))
n=int(input('Rows? '))
k=1
ch='$' for k in range(1, n+1):
while k<=n: for j in range(1, k+1):
j=1 print('*', end=‘’)
while j<=k:
print()
print(ch, end=‘’)
j+=1 Running of the script produces following
k+=1
print()
output:
Rows? 5
Running of the script produces following output:
Rows? 3
*
$ **
$$ ***
$$$ ****
$$$$
$$$$$
*****
rows = 6
rows = 5 for i in range(1, rows+1):
b = 0 num = 1
# reverse for loop from 5 to 0 for j in range(rows, 0, -1):
for i in range(rows, 0, -1): if j > i:
print(" ", end=' ')
#b += 1
else:
for j in range(1, i + 1):
print("*", end=' ')
print("*", end=' ')
num += 1
print(" ") print("")
Output: Output:
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * *
*
rows = 5
rows = 5
i = rows
k = 2 * rows - 2
while i >= 1:
j = rows for i in range(rows, -1, -1):
while j > i: for j in range(k, 0, -1):
# display space
print(end=" ")
print(' ', end=' ')
k = k + 1
j -= 1
k = 1 for j in range(0, i + 1):
while k <= i: print("*", end=" ")
print('*', end=' ')
print("")
k += 1
Output:
print()
i -= 1 ******
Output: *****
* * * * *
****
* * * *
***
* * *
* * **
* *
print("Print equilateral triangle Pyramid using
asterisk symbol ")
# printing full Triangle pyramid using stars
*
size = 7
**
m = (2 * size) - 2
***
for i in range(0, size):
for j in range(0, m): ****
print(end=" ") *****
# decrementing m after each loop ******
m = m - 1 *******
for j in range(0, i + 1):
print("*", end=' ')
print(" ")
rows = 5 *
*****
for i in range(rows, 0, -1):
****
for j in range(0, i - 1):
print("*", end=' ') ***
print("\r")
**
*
rows = 5 rows = 5
for i in range(1, rows + 1): b = 0
# reverse for loop from 5 to 0
for j in range(1, i + 1):
for i in range(rows, 0, -1):
print(j, end=' ') #b += 1
print(‘’) for j in range(1, i + 1):
Output: print(i, end=' ')
print('\r’)
1
Output
1 2
5 5 5 5 5
1 2 3 4 4 4 4
1 2 3 4 3 3 3
1 2 3 4 5 2 2
1
rows = 5 rows = 6
for i in range(len(X)):
[4 ,5,6],
# iterate through columns
[7 ,8,9]]
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
Y = [[5,8,1],
[6,7,3],
for r in result:
[4,5,9]] print(r)
Output:
result = [[0,0,0], [17, 15, 4]
[0,0,0], [10, 12, 9]
[0,0,0]] [11, 13, 18]
MATRIX SUBTRACTION USING NESTED LOOP
for i in range(len(X)):
[4 ,5,6],
# iterate through columns
[7 ,8,9]]
for j in range(len(X[0])):
result[i][j] = X[i][j] - Y[i][j]
Y = [[5,8,1],
[6,7,3],
for r in result:
[4,5,9]] print(r)
Output:
result = [[0,0,0], [7, -1, 2]
[0,0,0], [-2, -2, 3]
[0,0,0]] [3, 3, 0]
PROGRAM TO MULTIPLY TWO MATRICES USING NESTED LOOPS
# Program to multiply two matrices using # iterate through rows of X
nested loops
for i in range(len(X)):
# 3x3 matrix
# iterate through columns of Y
X = [[12,7,3],
for j in range(len(Y[0])):
[4 ,5,6],
# iterate through rows of Y
[7 ,8,9]]
for k in range(len(Y)):
# 3x4 matrix
result[i][j] += X[i][k] *
Y = [[5,8,1],
Y[k][j]
[6,7,3],
for r in result:
[4,5,9]]
print(r)
# result is 3x4
Output:
result = [[0,0,0],
[114, 160, 60]
[0,0,0],
[74, 97, 73]
[0,0,0]]
[119, 157, 112]
#PROGRAM TO TRANSPOSE A MATRIX USING A NESTED LOOP
[0,0,0]] print(r)
Output:
[12, 4, 3]
[7, 5, 8]
LOOP CONTROL STRUCTURES
BREAK
Break statements can alter the flow of a loop.
It terminates the current
loop and executes the remaining statement
outside the loop.
If the loop has else statement, that will also
gets terminated and come out of the
loop completely
for i in "welcome":
Output
if(i=="c"):
w
break e
print(i) l
CONTINUE
CONTINUE
It terminates the current iteration and transfer the Example:
control to the next iteration in for i in "welcome":
the loop. if(i=="c"):
Syntax: Continue continue
print(i)
Output
w
e
l
o
m
e