Control Structure (Flow of Control)[1]
Control Structure (Flow of Control)[1]
start / REPETITIONS
process / calculations
Nested Loops
Output (concept)
stop
1.)SEQUENCE: This is the simplest type of programming construct which flows in a single direction and executes the commands
and statements one after the other in a sequence. It starts at one point, accepts Input, process’s it, display’s the output and ends at
the other point.
Note: This construct does not include any conditional statements.
Note: For every additional nested block, it includes an extra tab (indentation)
2.) SELECTION: This construct of programming is mainly used along with conditional statements where in the user will chose out
of one to many choices available and python will execute the specific block of statement. It is comparatively more complex than the
Sequence construct. It provides 4 types of conditional statements as follows:
a) Simple if: It executes the Block of statements only if the specified condition evaluates to true, otherwise it does nothing.
Syntax:
if <condition>:
--------- block of statements (BOS)
---------
Example
if avgmarks>=90:
print(“Scholarship Granted”)
b) Simple if..else : It executes the Block of statement 1, if the specified condition evaluates to true, otherwise it executes the
Block of Statement 2.
Syntax:
if <condition>:
--------- BOS 1
---------
else:
---------- BOS 2
----------
Example:
if avgmarks>=90:
print(“Scholarship Granted”)
else:
print(“Scholarship Not Granted”)
c.) Multiple if..elif..else: In this construct, BOS1 shall be executed when condition1 evaluates to True, similarly BOS2 or BOS3
or so on shall be executed if condition 2 or condition 3 or so on evaluate to True respectively. “If” is used only with the
condition 1, and hence forth for all remaining conditions we use “elif”. If none of the above specified conditions evaluate
to True then the final BOSn shall be executed from the “else” block.
Syntax:
if <condition1>:
--------- BOS 1
---------
elif <condition2>:
---------- BOS 2
----------
elif <condition3>:
---------- BOS3
----------
.
.
else:
--------- BOS n
---------
if cnt==0:
result="Pass"
elif cnt==1:
result="Compartment"
else:
result="Failed"
print("Result of", name, "is" ,result)
d.) Nested if..if..else: In this programming construct , we have an outer “If” condition which is followed by the inner “if”
condition. It will only execute the inner block (nested if block) only if the outer “if” condition evaluated to “True” otherwise it
will execute the following “elif” condition of the outer “if” and so on. In the below syntax BOS 1 shall be executed when both
<condition> 1 and 2 both evaluate to True. BOS2 shall be executed with <condition1> evaluates to “True” but <condition2>
evaluates to “False”. BOS3 shall be executed when <condidtion1> evaluates to “False” and <condition3 > evaluates to “True”.
Finally BOS n shall be executed when all outer “if” conditions evaluate to “False”.
Syntax:
if <condition1>: #OUTER IF
if <condition2>: #INNER IF
--------- BOS 1 #NESTED BLOCK IN RED
---------
else:
--------- BOS2
---------
elif <condition3>:
---------- BOS 3
----------
.
.
else:
--------- BOS n
---------
Programs to be done using Nested if..if..elif..else construct
Q.1 Program to accept a date from the user and validate it.
Q.2 Program to accept any 3 numbers from the user and display the highest/lowest of them.
Q.3 Program to accept a number from the user and display if it is a positive even number or odd number or if it is
a negative even or odd number, otherwise display the number is Neutral.
Q.4 Program to accept the year and month (1-12) from the user and display the number of days in the month.
#Program 5: To accept the Name, age, gender from the user and display the message as follows:
Gender Age Message
Male <=2 Infant Boy
3 to 12 Boy Child
13 to 19 Teenage Boy
20 to 30 Young Man
31 to 59 Adult Man
>=60 Old Man
Female <=2 Infant Girl
3 to 12 Girl Child
13 to 19 Teenage Girl
20 to 30 Young Girl
31 to 59 Adult Woman
>=60 Old Woman
Other Invalid Gender
#Program 6: To accept the employee name, department, basic salary and sales made from the user. Calculate and
display the commission and the gross salary as follows:
Department Sales Made Commission % of Sales Made
Sales(S) <=5000 5%
>25000 20%
Marketing(M) <=5000 4%
5001 to 15000 8%
>25000 16%
Others Any 2%
if d<1 or d>dd:
valid="False Date"
if valid=="True":
print("Your date entered is", d,"/",m,"/",y )
elif valid=="False Date":
print("Your entered day is Invalid" )
elif valid=="False Month":
print("Your entered month is Invalid")
else:
print("Your entered year is Invalid")
Program 2a: Highest of 3 numbers
n1=int(input("Enter first number:"))
n2=int(input("Enter second number:"))
n3=int(input("Enter third number:"))
if n1>n2: # Outer If block
if n1>n3: # Inner If block
print(n1, "is greatest number.")
else:
print(n3, "is greatest number.")
elif n2>n3:
print(n2, "is greatest number")
elif n1==n2 or n1==n3:
print(“Any 2 or more numbers are equal”)
else:
print(n3, "is greatest number”)
Forward Index 0 1 2 3 4 5
0 1 2 3 4 5 6 7
Name= “Shohib”
e h o h i b
0 1 2 3 4 5
Str1= ‘Hello Friend’
H e l l o F r i e n d
0 1 2 3 4 5 6 7 8 9 10 11
E.g.
for y in [‘a’,’e’,’i’,’o’,’u’]:
print(y)
-5 -4 -3 -2 -1 Backward Index
a e i o u
Forward Index 0 1 2 3 4
#Program to accept a string from the user and display the number of characters within the string.
s=input("Enter a String:")
cnt=0
for x in s:
cnt+=1
print(s, "contains", cnt, "characters.")
print()
#Program to accept a string from the user and count the number of vowels and consonants in it.
s=input("Enter a String:")
v=0
c=0
for x in s.lower():
if x in “aeiou”:
v+=1
elif x==" ":
continue
else:
c+=1
print("No. of Vowels is", v)
print("No. of Consonants is", c)
Syntax 2: using range( ) function : This syntax is used with the range() function which evaluates the loop from start value till the stop
value – 1(exit) and by default increments the counter variable by 1. It can increment the counter variable value either by more than
1 or also decrement it.
Syntax:
for <variable> in range( <start>, <stop/exit>, [updation] ) :
--------------------------------- BOS
---------------------------------
E.g.
for x in range(1,11) :
print(x)
for x in range(2,11,2) :
print(x)
for x in range(11,2,-2) :
print(x)
#Program to accept a string from the user and display it in reverse
S=input("Enter a String:")
revS=""
for i in range(len(S)-1,-1,-1):
revS=revS + S[i]
print("The reversed string is", revS)
Working:
S=
Y A S H
0 1 2 3
revS = “”
I revS
3 H
2 HS
1 HSA
0 HSAY
-1------------→ EXIT
# Write a program to accept a range from the user and display the square of odd numbers and cube of even nos within the range.
s=int(input("Enter a start value:"))
e=int(input("Enter a end value:"))
for x in range(s,e+1):
if x%2==0:
print("The cube of", x, "is", x**3)
else:
print("The square of", x, "is", x**2)
# Write a program to accept a range from the user and display the sum of first even and odd numbers within the range.
# E.g. if the range is 1 to 10, then odd numbers between 1 to 10 are 1+3+5+7+9=25 and the even numbers are 2+4+6+8+10=30
s=int(input("Enter a start value:"))
e=int(input("Enter a end value:"))
evensum=0
oddsum=0
for x in range(s,e+1):
if x%2==0:
evensum = evensum + x
else:
oddsum = oddsum + x
print("Sum of Even Numbers is", evensum)
print("Sum of Odd Numbers is ", oddsum)
Working:
s e x evensum oddsum x%2==0
1 10 1 0 0 .F.
2 2 1 .T.
3 6 4 .F.
4 12 9 .T.
5 20 16 .F.
6 30 25 .T.
7 .F.
8 .T.
9 .F.
10 .T.
11 → exit the loop
# Program to accept a positive number from the user and display its factorial
#(E.g. num=5 then factorial = 1x2x3x4x5=120, or 5x4x3x2x1=120)
num=int(input("Enter a Number:"))
if num<0:
print("Cannot get factorial of a negative number!!!")
elif num==0:
print("Factorial of 0 is 1")
else:
f=1
for i in range(num,0,-1):
f *= i
print("The factorial of", num, "is", f)
# Program to accept a end limit from the user and display the following series:
# a.) 0 ,1 ,1 ,2, 3 , 5, 8, 13, 21......, n (Fibonacci series))
n=int(input("Enter the limit:"))
f=-1
s=1
for i in range(1, n+1):
t=f + s
print(t, end=",")
f, s = s, t
Working
n i f s t o/p
6 1 -1 1 0 0,1,1,2,3,5,
2 1 0 1
3 0 1 1
4 1 1 2
5 1 2 3
6 2 3 5
7 3 5
'
# b.) 0 , 6 , 24 , 60 , 120, 210, ......, n
# 1**3-1 , 2**3-2, 3**3-3 , 4**3-4 , 5 6
n=int(input("Enter a Limit:"))
for i in range(1,n+1):
print(i**3-i, end=",")
print()
#Program to display the multiplication table of any number accepted from the user:(using for loop)
num=int(input("Enter a number:"))
for i in range(1,11,1):
print(num, "x", i, "=",num*i)
#Program to accept a number from the user and display if it is Unique, prime or composite. (E.g. 1 is Unique, 3 is Prime and 6 is Composite)
#(Eg 0 is neither prime nor composite.)
num=int(input("Enter a number:"))
if num==0:
print(num, "is neither prime nor composite.")
elif num==1:
print(num, "is unique.")
else:
prime=True
for i in range(2,num):
if num % i == 0:
prime=False
break
if prime==True:
print(num, "is prime.")
else:
print(num, "is composite.")
#Program to accept a range from the user and display the sum of all the numbers divisible by 'n' within the range.
(E.g. Range is 10-20, n is 3, then, 12+15+18=45)
s=int(input("Enter start value:"))
e=int(input("Enter end value:"))
n=int(input("Enter the divisibility number:"))
sum=0
if s<e:
for i in range(s, e+1):
if i % n == 0:
sum += i
print(i, "+")
print("Sum=", sum)
else:
print("Invalid range!!!")
print("Start value should be lesser than end value!!!" )
b.) while loop (condition loop): This is a condition-based loop where in the initialization, condition and updation statements are all
split into 3 different lines. The loop iterates until the conditions evaluates to True and terminates when the condition specified
becomes False. The updation statement is always the last statement in the block of statements within the loop.
Syntax:
<initialization>
while <condition>:
------------ BOS
------------
<updation>
E.g. Program to print 1 to 10
x=1
while x<=10:
print (x)
x=x+1
for x in range(1,11,1):
print(x)
#Program to display the multiplication table of any number accepted from the user:(using while loop)
num=int(input("Enter a number:"))
i=1 #initialization
while i<11: # condition
print(num, "x", i, "=", num*i)
i=i+1 #updation
# Program to accept a number from the user and display the sum of its individual digits (E.g. num=234 then sum = 2+3+4= 9 )
num=int(input("Enter any number:"))
sum=0
while num!=0:
dig=num % 10
sum=sum + dig
num=int(num/10)
print()
print("Sum of individual digits is", sum)
working:
num sum dig num!=0
234 0 4 .T.
23 4 3 .T.
2 7 2 .T.
0 9 .F.
# Program to accept a number from the user & display the product of its individual digits (E.g. num=234 then product = 2*3*4= 24)
num=int(input("Enter any number:"))
prod=1
while num!=0:
dig=num % 10
prod=prod*dig
num=int(num/10)
print("Product of individual digits is", prod)
# Program to accept a number from the user and display it in reverse. (E.g. num=234 the result=432)
num=int(input("Enter any number:"))
rev=0
while num!=0:
dig=num % 10
rev=rev*10+dig
num=int(num/10)
print("Reverse is", rev)
Working
num rev dig num!=0
234 0 4 T
23 4 3 T
2 43 2 T
0 432 F
#Program to accept a number from the user and display if it is a Palindrome or not. (E.g. num=234 result="Not a Palindrome", num=232 result="Palindrome")
num=int(input("Enter any number:"))
temp=num
rev=0
while num != 0:
dig=num % 10
rev=rev*10+dig
num=int(num/10)
print("Reverse of", temp, "is", rev)
if rev==temp:
print(temp, "is a Palindrome.")
else:
print(temp, "is not a palindrome")
#Program to accept a number from the user and display if it is an Armstrong number or not. (E.g. num=153 1**3+5**3+3**3 = 1+125+27=153
result="Armstrong" , num=232 2**3+3**3+2**3 = 8+27+8 =43 result="Not Armstrong")
num=int(input("Enter any number:"))
temp=num
sum=0
while num!=0:
dig=num % 10
sum=sum + dig**3
num=int(num/10)
if temp==sum:
print(temp, "is an Armstrong number.")
else:
print(temp, "is Not an Armstrong number.")
#Program to accept a number from the user and display if it is a Perfect number or not. (6=1+2+3=6 is Perfect no whereas 8 = 1+2+4=7 is not Perfect no.)
num=int(input("Enter any number:"))
sum=0
x=1
while x<=num/2:
if num % x==0:
sum=sum + x
x+=1
print()
if num==sum:
print(num, "is a Perfect number.")
else:
print(num, "is Not a Perfect number.")
Nested loops: A loop may contain another loop inside it. A loop inside another loop is called a nested loop. For every one iteration of the Outer
loop, the inner loop iterates its full range or till the condition is satisfied.
Generalized Syntax:
<outer loop> :
<inner loop> :
-------- inner BOS
-------- outer BOS
__________
__________
E.g. Print the following structure j
*
** 1 2 3 4 5
*** 1 *
**** i 2 * *
*****
3 * * *
for i in range(1,6):
for j in range(1, i+1): 4 * * * *
print("*",end="") 5 * * * * *
print()
i j
1 1
2 → Exit j
2 1
2
3 → Exit j
3 1
2
3
4 → Exit j
4 1
2
3
4
5 →Exit j
5 1
2
3
4
5
6 → Exit j
6 Program terminates → Exit i
# Program to input the character and number of rows and print the following structure using nested loops
ch=input("Enter any character:")
rows=int(input("Enter the number of rows:"))
for i in range(1,rows+1):
for j in range(1,i+1):
print(ch,end="")
print()
1
22
333
4444
55555
for i in range(1,6):
for j in range(1,i+1):
print(i,end="")
print()
1
12
123
1234
12345
for i in range(1,6):
for j in range(1,i+1):
print(j, end="")
print()
54321
4321
321
21
1
for i in range(5,0,-1):
for j in range(i,0,-1):
print(j,end="")
print()
0
12
345
6789
k=0
for i in range(1,5):
for j in range(1,i+1):
print(k,end="")
k+=1
print()
9876
543
21
0
k=9
for i in range(4,0,-1):
for j in range(1,i+1):
print(k,end="")
k-=1
print()
5
45
345
2345
12345
for i in range(5,0,-1):
for j in range(i,6):
print(j,end="")
print()
A
BB
CCC
DDDD
EEEEE
y=1
for x in ["A","B","C","D","E"]:
print(x*y)
y+=1
or
for x in range(65,70):
for y in range(65,x+1):
print(chr(x),end="")
print()
A
AB
ABC
ABCD
ABCDE
for x in range(65,70):
for y in range(65,x+1):
print(chr(y),end="")
print()
a
ab
abc
abcd
abcde
for x in range(97,102):
for y in range(97,x+1):
print(chr(y),end="")
print()
aaaaa
bbbb
ccc
dd
e
abcde
abcd
abc
ab
e
abcde
bcde
cde
de
e
onmlk
jihg
fed
cb
a
k=111
for i in range(5,0,-1):
for j in range(1,i+1):
print(chr(k),end="")
k-=1
print()
eeeee
dddd
ccc
bb
a
a
bc
def
ghij
klmno
pqrstu
k=65
for i in range(1,7):
for j in range(1,i+1):
print(chr(k),end="")
k+=1
print()
JUMP statements:
Statements which move the control to another part of the execution point (statement) from the current statement are knows as Jump
statements. Python provides different types of jump statements as follow:
a.) break
b.) continue
c.) return
d.) pass
a.) break: This keyword is a jump statement which alters the normal flow of execution as it terminates the current loop and resumes execution
of the statement following that loop.
E.g. #Program to demonstrate the use of break statement in loop
num = 0
for num in range(10):
num = num + 1
if num == 8:
break
print('Num has value ' + str(num))
print('Encountered break!! Out of loop')
output:
Num has value 1
Num has value 2
Num has value 3
Num has value 4
Num has value 5
Num has value 6
Num has value 7
Encountered break!! Out of loop
b.) continue: This keyword is also another type of jump statement in which the control skips the execution of remaining statements inside the
body of the loop for the current iteration and jumps to the beginning of the loop for the next iteration. If the loop’s condition is still true, the
loop is entered again, else the control is transferred to the statement immediately following the loop.
# Program to demonstrate the use of continue statement.
num = 0
for num in range(6):
num = num + 1
if num == 3:
continue
print('Num has value ' + str(num))
print('End of loop')
output:
Num has value 1
Num has value 2
Num has value 4
Num has value 5
Num has value 6
End of loop
iii) sum=0
for x in (33,11,22,9,12,15,6):
if x%3!= 0:
continue
if x%4 == 0:
break
sum=sum+x
print (sum)
sum x o/p
0 33 42
33 11
42 22
9
12
c.) return: This jump statement is used to return the value back to the calling program from the function or the method and the
control starts executing the following statements in the calling program.
d.) pass: This jump statement is also a keyword which is used to ignore the block of statements from executing anything. It is also
known as an empty statement.
2)
i = 0; sum = 0
while i < 9:
if i % 4 == 0:
sum = sum + i
i=i+2
print (sum,i)
3)
i = 0; sum = 0
while i < 9:
if i % 4 == 0:
sum = sum + i
i=i+2
print (sum,i)
a b c X
10 12 15 55
100 2
o/p
100:2:15 # X=55
x y
7 0
-7 7
o/p
-7 7
Q4. Rewrite the output after removing all the error (2)
S=`pura vida'
S1=S[0:5] => pura_ (“underscore denotes a space”)
S2=S[5:] => vida
S3=S1*S2 =>error (should replace the * with + operator then o/p will be pura vida)
S4=S2+'3’ => vida3
S5=S1+3 => error (should replace 3 with “3” and then o/p will be pura 3)