You are on page 1of 51

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

 Odd or even number  Leap year or not


y=eval(input("enter a yaer"))
 n=eval(input("enter a number")) if(y%4==0):
print("leap year")
if(n%2==0): else:
print("not leap year")
print("even number")
 Greatest of two numbers
else: a=eval(input("enter a value:"))
print("odd number") b=eval(input("enter b value:"))
if(a>b):
 Positive or Negative number print("greatest:",a)
else:
n=eval(input("enter a number")) print("greatest:",b)
if(n>=0):
print("positive number")  Eligibility for voting
else: age=eval(input("enter ur age:"))
if(age>=18):
print("negative number") print("you are eligible for vote")
else:
print("you are not eligible for vote")
IF-ELIF-ELSE

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

Calculator  traffic light system


a=float(input('1st value? '))
b=float(input('2nd value? ')) colour=input("enter
op=input('Operator [+,-,*,/,**]? ') if
op=='+’: colour of light:")
print(a,op,b,'=',a+b) if(colour=="green"):
elif op=='-’:
print(a,op,b,'=',a-b) print("GO")
elif op=='*’:
print(a,op,b,'=',a*b)
elif(colour=="yellow"):
elif op=='/’: print("GET READY")
print(a,op,b,'=',a/b)
elif op==‘**’: else:
print(a,op,b,'=',a**b)
else: print("STOP")
print('Error: ',op,'invalid operator!’)
NESTED IF – ELSE CONDITIONALS

Nested if – else conditionals Syntax:


 One conditional can also be nested within
if (condition 1):
another. Any number of condition can be nested
if (sub condition 1):
inside one another.
statements1
 In this, if the condition is true it checks another else:
if condition1. statements 2
 If both the conditions are true statement1 get else :
executed otherwise statement2 get execute. statements 3
 if the condition is false statement3 gets executed
NESTED IF – ELSE CONDITIONALS

 Greatest of three numbers  Positive negative or zero


a=eval(input(“enter the value of a”)) n=eval(input("enter the value of n:"))
b=eval(input(“enter the value of b”)) if(n==0):
c=eval(input(“enter the value of c”)) print("the number is zero")
if(a>b): else:
if(a>c): if(n>0):
print(“the greatest no is”,a) print("the number is positive")
else: else:
print(“the greatest no is”,c) print("the number is negative")
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
ITERATION

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

 While loop:  The statements inside the while starts with


 While loop statement in Python is used to indentation and the first un indented line marks the
repeatedly executes set of statement as long as a end.
given condition is true.  Syntax:
 In while loop, test expression is checked first. The Initialize value
body of the loop is entered only if the while expression:
test_expression is True. After one iteration, the test Statement
expression is checked again. This process Increment/Decrement
continues until the test_expression evaluates to
False.
 In Python, the body of the while loop is
determined through indentation.
WHILE LOOP
 while loop has three components:
a) Control Variable and its Initialization: while loop in Python has a control variable. Control
variable is generally an integer type or float type. But we can have Python while loop without a control
variable. If a while loop has a control variable, it is always initialized. A control variable is either an
integer variable or a floating point variable. It is called control variable because, it controls the
iteration
(number times a loop gets executed) of while loop.
 b) Terminating Condition: Generally, a while loop should terminate after certain number of
iterations.
Terminating condition of a while loop in Python is a condition (logical expression) involving the
control variable and the stop value (final value). Condition (logical expression) plays a pivotal role in
while loop in Python while loop iteration depends on the condition.
 c) Updating Control Variable: Python while loop repeats a block. Inside the block of a while loop,
control variable is updated (value of the control variable is either incremented or decremented), so that
the while loop terminates after certain number of iteration
WHILE LOOP

 Sum of n numbers  Factorial of a numbers


n=int(input("enter n")) n=int(input("enter n"))
i=1 i=1
sum=0 fact=1
while(i<=n): while(i<=n):
sum=sum+i fact=fact*i
i=i+1 i=i+1
print(sum) print(fact)
 Fibonacci number
 Table of number
i=int(input(“enter the i”))
 x=int(input(“x?”))
x=0
 i=1
y=1
z=1  while i<=10:
 print(x,”x”,i,”=“,x*i)
print(“fibonacci series”)
print(x,y,end=“ “)
while(z<=i)
print(z, end=“ “)
x=y
y=z
z=x+y
WHILE LOOP

Sum of digits of a number  Reverse the given number


n=eval(input("enter a number")) n=eval(input("enter a number"))
sum=0 sum=0
while(n>0): while(n>0):
a=n%10 a=n%10
sum=sum+a sum=sum*10+a
n=n//10 n=n//10
print(sum) print(sum)
WHILE LOOP
 Armstrong number or not  Palindrome or not
n=eval(input("enter a number")) n=eval(input("enter a number"))
org=n org=n
sum=0 sum=0
while(n>0): while(n>0):
a=n%10 a=n%10
sum=sum+a*a*a sum=sum*10+a
n=n//10 n=n//10
if(sum==org): if(sum==org):
print(“Number is Armstrong number") print("The given no is palindrome")
else: else:
print(“Number is not Armstrong print("The given no is not palindrome")
number")
 Write a Python script to generate  Write a Python script to generate
and display following sequence on and display following sequence on
screen: 1, 3, 5, 7, ..., 19 screen: 100, 90, 80, ..., 20, 10
k=100
k=1
while k>=10:
while k<=19: print(k)
print(k) k-=10
k+=2  Find output:

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()

 StartVal: First value in the sequence


StopVal: Final value (StopVal-1) in the sequence
Step: Common difference between two successive numbers in the sequence
All parameters in the range() function must be integers. Using floating point value(s) as parameter(s)
in the range() function will trigger an error.
 3. range(StartVal, StopVal, Step)
a) Generates integers StartVal, StartVal + Step, StartVal + 2*Step, ..., StopVal-1 when
StartVal<StopVal and Step>0
Generates a sequence in ascending order.
b) Generates integers StartVal, StartVal - Step, StartVal - 2*Step, ..., StopVal+1 when
StartVal>StopVal and Step<0
Generates a sequence in descending order.
RANGE()

 range(1, 6, 1) will generate sequence of integers 1, 2, 3, 4, 5


range(2, 12, 2) will generate sequence of integers 2, 4, 6, 8, 10
range(1, 12, 2) will also generate sequence of integers 1, 3, 5, 7, 9, 11
range(-1, -6, -1) will generate sequence of integers -1, -2, -3, -4, -5
range(15, 2, 3) will generate sequence of integers 15, 12, 9, 6, 3
range(-15, -2, 3) will generate sequence of integers -15, -12, -9, -6, -3
range(-5, 6, 2) will generate sequence of integers -5, -3, -1, 1, 3, 5
range(-9, 0, -2) does not generate an any sequence because StartVal<StopVal and
Step is -2
FOR LOOP
 for in range:
We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size as range(start, stop, step
size). step size defaults to 1 if not provided
 Syntax:
 for ControlVar in range(StartVal, StopVal, Step):
#Python Statements (for block)
 Example:
 for i in range(1,5,2):
 print(i)
FOR LOOP
 For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over a sequence
is called traversal.
 Loop continues until we reach the last element in the sequence.The body of for loop is separated from
the rest of the code using indentation.
 Syntax:
 for ControlVar in sequence :
#Python Statements (for block)
 Example:
 a=[1,2,3]
 for i in a:
 print(i)
 print numbers divisible by 5 not by  Fibonacci series
10 a=0
n=int(input("enter a")) b=1
for i in range(1,n,1): n=int(input("Enter the number of terms:
if(i%5==0 and i%10!=0): "))
print(i) print("Fibonacci Series: ")
 find factors of a number print(a,b)
n=int(input("enter a number:")) for i in range(1,n,1):
for i in range(1,n+1,1): c=a+b
if(n%i==0): print(c)
print(i) a=b
b=c
 Sum of n numbers  Factorial of a numbers
n=int(input("enter n")) n=int(input("enter n"))
sum=0 fact=1
for i in range(1,n+1): for i in range(1,n+1):
sum=sum+i fact=fact*i
print(sum) print(fact)
 check the no is prime or not  Program to print prime numbers in
n=int(input("enter a number")) range
for i in range(2,n): lower=eval(input("enter a lower range"))
if(n%i==0): upper=eval(input("enter a upper range"))
print("The num is not a prime") for n in range(lower,upper + 1):
break if n > 1:
else: for i in range(2,n):
print("The num is a prime number.") if (n % i) == 0:
break
else:
print(n)
 Write a Python script to generate and  Write a Python script to generate and
display: display:
1, 2, 3, 4, ..., 9, 10 2, 4, 6, 8, ..., 18, 20
for x in range(1, 11): for x in range(2, 21, 2):
print(x, end=' ') print(x, end=' ')
Running of the script: Running of the script:
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20
 Write a Python script to generate and  Write a Python script to generate and
display: display:
10, 9, 8, 7, ..., 2, 1 19, 17, 15, 13, ..., 3, 1
for x in range(10, 0, -1): for x in range(19, 0, -2):
print(x, end=' ') print(x, end=' ')
Running of the script: Running of the script:
10 9 8 7 6 5 4 3 2 1 19 17 15 13 11 9 7 5 3 1
 Write a Python script to generate and  Write a Python script to input an integer
display: (say n); then generate and display: 12, 22,
4, 8, 12, 16, ..., 36, 40 32, 42, ..., (n-1)2, n2
for x in range(4, 41, 4): n=int(input('Input n? ‘)
print(x, end=' ') print('\nUsing "for" loop’)
Running of the script: for x in range(1, n+1):
4 8 12 16 20 24 28 32 36 40 print(x**2, end=' ‘)
 Write a Python script to generate and  Write a Python script to input an integer
display: (say n); then generate and display: 13, 23,
50, 45, 40, 35, ..., 10, 5 33, 43, ..., (n-1)3, n3
for x in range(50, 4, -5): n=int(input('Input n? ')
print(x, end=' ') print('\nUsing "for" loop')
Running of the script: for x in range(1, n+1):
50 45 40 35 30 25 20 15 10 5 print(x**3, end=' ')
 #count number of digits  #sum of cube of digits
n=int(input('Input n? ')) n=int(input('Input n? '))
d=0 s=0
while n>0: while n>0:
d+=1 d=n%10
n//=10 s+=d*d*d
print('Digits =‘,d) n//=10
 #sum of square of digits print('Sum =‘,s)
n=int(input('Input n? '))  #products of digits
s=0 n=int(input('Input n? '))
while n>0: p=1
d=n%10 while n>0:
s+=d*d d=n%10
n//=10 p*=d
print('Sum =',s) n//=10
print('Product =',p)
ELSE WITH LOOP
With a while loop and with for loop we have an else part and else part with loop is executed when a loop
terminates normally
 while loop with else statement:  for loop with else statement:
while Condition: for var in range(...):
Block Block
else: else:
Block2/Statement2 Block2/Statement2
k=1 for k in range(1,7):
while k<=4: print(k)
print(k) else:
k+=1 print('End of for loop')
else:
print('End of while loop')
NESTED LOOP

 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(0, rows):


 **
 for j in range(0, i + 1):
 ***
 print("*", end=' ')
 print("\r")  ****

 *****
 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

 i = 1  for i in range(1, rows):

 while i <= rows:  num = 1


 j = 1  for j in range(rows, 0, -1):
 while j <= i:  if j > i:
 print((i * 2 - 1), end=" ")  print(" ", end=' ')
 j = j + 1  else:
 i = i + 1  print(num, end=' ')
 print(‘’)  num += 1
 Output  print("")
 1  Output:
 3 3 1
 5 5 5  1 2
 7 7 7 7  1 2 3
 9 9 9 9 9  1 2 3 4
 1 2 3 4 5
MATRIX ADDITION USING NESTED LOOP

 X = [[12,7,3],  # iterate through rows

  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

 X = [[12,7,3],  # iterate through rows

  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

 # Program to transpose a matrix using a nested loop  # iterate through rows


 for i in range(len(X)):
 X = [[12,7],  # iterate through columns
 [4 ,5],  for j in range(len(X[0])):
 [3 ,8]]  result[j][i] = X[i][j]

 result = [[0,0,0],  for r in result:

 [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

You might also like