Module 2 - Control Structures - Python Programming
Module 2 - Control Structures - Python Programming
9150132532
[email protected]
Profameencse.weebly.com Noornilo Nafees 1
MODULE 2 – CONTROL STRUCTURES
At the end of this course students can able to
Gain knowledge on the various flow of control in
Python language.
Learn through the syntax how to use conditional
Noornilo Nafees 2
CONTROL STRUCTURES
Statements in programs are executed sequentially,
that is the statements are executed one after
another.
There may be situations in our real life programming
Noornilo Nafees 3
A program statement that causes a jump of control from one part
of the program to another is called control structure or control
statement.
There are three important control structures
1. Sequential Statements
2. Alternative or Branching Statements
3. Iterative or Looping Statements
1. Sequential Statements: A sequential statement is composed of
a sequence of statements which are executed one after another.
# Program to print your name and address - example for
sequential statement
print ("Hello! This is Noornilonafees")
print ("9, Yahussain Palli Street, Nagapattinam, TN")
Output
Hello! This is Noornilonafees
9, Yahussain Palli Street, Nagapattinam, TN
Noornilo Nafees 4
2. Alternative or Branching Statement:
In our day-to-day life we need to take various decisions
Noornilo Nafees 5
Python provides the following types of alternative or
branching statements:
(a) Simple if statement
(b) if..else statement
(c) Nested if..elif...else statement
(a) Simple if statement:
Simple if is the simplest of all decision making statements.
Condition should be in the form of relational or logical
expression.
Syntax:
if <condition>:
◦ statements-block1
In the above syntax if the condition is true statements -
block 1 will be executed.
Noornilo Nafees 6
# Program to check the age and print whether eligible
for voting
x=int (input("Enter your age :"))
if x>=18:
Noornilo Nafees 7
# Program to check whether the given number is
greater than 10
a=int(input("Enter a number:"))
if(a>10):
Enter a number: 12
12 is greater than 10
Noornilo Nafees 8
(b) if..else statement:
The if .. else statement provides control to check the
◦ statements-block 1
else:
◦ statements-block 2
if..else statement thus provides two possibilities and
Noornilo Nafees 9
if..else statement execution
Noornilo Nafees 10
#Program to check if the accepted number odd or
even
a = int(input("Enter any number :"))
if a%2==0:
Noornilo Nafees 11
#Program to check whether given number is greater
than or lesser than 10
a=int(input("Enter a number:"))
if(a>10):
Noornilo Nafees 12
#Program to check if the accepted number is odd or
even using alternate method of if...else(Conditional
Statement)
a = int (input("Enter any number :"))
x="even" if a%2==0 else "odd"
print (a, " is ",x)
Output 1:
Enter any number :3
3 is odd
Output 2:
Enter any number :22
22 is even
Noornilo Nafees 13
(c) Nested if..elif...else statement: When we need to
construct a chain of if statement(s) then ‘elif’ clause can be
used instead of ‘else if’.
Syntax:
if <condition-1>:
◦ statements-block 1
elif <condition-2>:
◦ statements-block 2
else:
◦ statements-block n
In the syntax of if..elif..else mentioned above, condition-1 is
tested if it is true then statements-block1 is executed,
otherwise the control checks condition-2, if it is true
statements-block2 is executed and even if it fails
statements-block n mentioned in else part is executed.
Noornilo Nafees 14
if..elif..else statement execution
Noornilo Nafees 15
#Program to illustrate student grade calculation using
nested if statement
name=input("Enter your name:")
rno=int(input("Enter your Register number:"))
m1=int(input("Enter mark 1:"))
m2=int(input("Enter mark 2:"))
m3=int(input("Enter mark 3:"))
tot=m1+m2+m3
avg=tot/3
print("Name:",name)
print("Register number:",rno)
print("Total:",tot)
print("Average",round(avg,1))
Noornilo Nafees 16
if (avg>=60):
◦ print("First Class")
elif(avg>=50): Output 1:
Enter your name:Ameen
◦ print("Second Class")
Enter your Register number:2012
elif(avg>=60):
Enter mark 1:99
◦ print("Third Class") Enter mark 2:77
else: Enter mark 3:88
Name: Ameen
◦ print("Fail") Register number: 2012
Total: 264
Average 88.0
First Class
Noornilo Nafees 17
#Program to find leap year:
y=int(input("Enter a year to check whether given year
Noornilo Nafees 18
In most other programming languages, indentation is used
only to help make the code look pretty.
But in Python, it is required to indicate to which block of
code the statement belongs to.
#Program to illustrate the use of ‘in’ and ‘not in’ in if
statement
Output 1:
Enter a character :e
ch=input (“Enter a character :”) e is a vowel
# to check if the letter is vowel Output 2:
if ch in (‘a’, ‘A’, ‘e’, ‘E’, ‘i’, ‘I’, ‘o’, ‘O’, ‘u’, ‘U’): Enter a character :x
◦ print (ch,’ is a vowel’) x the letter is not a/b/c
# to check if the letter typed is not ‘a’ or ‘b’ or ‘c’
if ch not in (‘a’, ’b’, ’c’):
◦ print (ch,’ the letter is not a/b/c’)
Noornilo Nafees 19
Iteration or Looping constructs: Iteration or loop are
used in situation when the user need to execute a
block of code several of times or till the condition is
satisfied.
Noornilo Nafees 20
Python provides two types of looping constructs:
(a)while loop
(b)for loop
(a)while loop: The while loop in Python has the
following syntax:
Syntax:
while <condition>:
◦ statements block 1
Noornilo Nafees 21
Program to illustrate the use of while loop - to print
all numbers between 10 to 15:
i=10 # intializing part of the control variable
while (i<=15): # test condition
10 11 12 13 14 15
That the control variable is i, which is initialized to 10,
Noornilo Nafees 23
#program to reverse a number and to check whether the
given number is palindrome or not:
rev=0
n=int(input("Enter number to reverse :"))
t=n Output:
while(t!=0): Enter number to
◦ rev=rev*10 reverse :452
◦ rev=rev+(t%10) Reversed number is 254
◦ t=t//10 452 is not Palindrome
print("Reversed number is",rev)
if(n==rev):
◦ print(n,"is Palindrome")
else:
◦ print(n,"is not Palindrome")
Noornilo Nafees 24
Program to illustrate the use of while loop - to find
factorial of given number:
i=1
fact=1
n=int(input("Enter a number to find factorial :"))
while(i<=n):
◦ fact=fact*i
◦ i=i+1
print("Factorial value of",n,"is",fact)
Output:
Enter a number to find factorial :5
Factorial value of 5 is 120
Noornilo Nafees 25
Program to illustrate the use of while loop - to find
sum of given digits:
r,sum=0,0
n=int(input("Enter digits to find sum of digits : "))
while(n>0):
◦ r=n%10
◦ sum=sum+r
◦ n=n//10
print("Sum of given digits is",sum)
Output:
Enter digits to find sum of digits : 156
Sum of given digits is 12
Noornilo Nafees 26
Program to check whether the given number is an
Armstrong number or not:
r,sum=0,0
n=int(input("Enter a number to check whether given
number is an Armstrong number or not:"))
a=n Output:
while(n>0): Enter a number to check whether
◦ r=n%10 given number is an Armstrong number
◦ sum=sum+r*r*r or not:
◦ n=n//10 153
if(a==sum): 153 is an Armstrong number
◦ print(a,"is an Armstrong number")
else:
◦ print(a,"is not an Armstrong number")
Noornilo Nafees 27
(b) for loop:
for loop is the most comfortable loop. It is also an
◦ statements-block 1
Noornilo Nafees 28
for loop uses the range() function in the sequence to specify
the initial, final and increment values.
range() generates a list of values starting from start till stop-1.
The syntax of range() is as follows:
range (start,stop,step)
Where,
start – refers to the initial value
stop – refers to the final value
step – refers to increment value(optional)
Examples for range():
range (1,30,1) will start the range of values from 1 and end at
29
range (2,30,2) will start the range of values from 2 and end at
28
range (20) will consider this value 20 as the end value(or upper
limit) and starts the range count from 0 to 19.
Noornilo Nafees 29
for loop execution:
Noornilo Nafees 30
#program to illustrate the use of for loop - to print
numbers from 1 to 10
for i in range (1,11):
control statements.
Indentation only creates blocks and sub-blocks like
Noornilo Nafees 31
#program to illustrate the use of for loop - to print even
number from 1 to n
n=int(input("Enter the limit to find even numbers from 1 to n :"))
for i in range(1,n+1):
◦ if(i%2==0):
print(i,end=' ')
Output:
Enter the limit to find even numbers from 1 to n :10
2 4 6 8 10
Noornilo Nafees 32
# program to calculate the sum of numbers 1 to 100:
for loop uses the range() function in the sequence to specify the
initial initial, final and increment values. range() generates a list of
values starting from start till stop-1.
n=100
sum=0
for i in range (1,n+1,1):
◦ sum=sum+i
print ("sum = ",sum,end=' ')
Output:
sum = 5050
In the above code, n is initialized to 100, sum is initialized to 0, the
for loop starts executing from 1, for every iteration the value of
sum is added with the value of variable i and stored in sum.
Note that the for loop will iterate from 1 till the upper limit -1 (ie.
Value of n is set as 100, so this loop will iterate for values from 1 to
99 only, that is the reason why we have set the upper limit as n+1)
Noornilo Nafees 33
#Program to illustrate the use of string in range() of
for loop
for word in 'Computer':
Noornilo Nafees 34
Program to illustrate the use of for loop - to find
factorial of given number:
i=1
fact=1
n=int(input("Enter a number to find factorial :"))
for i in range(1,n+1):
◦ fact=fact*i
print("Factorial value of",n,"is",fact)
Output:
Enter a number to find factorial :5
Factorial value of 5 is 120
Noornilo Nafees 35
Program to generate nth multiplication table to given limit:
tab=int(input("Enter the multiplication table: "))
n=int(input("Enter the limit of the multiplication table: "))
for i in range(1,n+1):
◦ res=i*tab
◦ print(i,"*",tab,":",res)
Output:
Enter the multiplication table:
5
Enter the limit of the multiplication table:
5
1*5:5
2 * 5 : 10
3 * 5 : 15
4 * 5 : 20
5 * 5 : 25 Noornilo Nafees 36
Program to calculate students mark list using for loop:
n=int(input("Enter number of students :"))
print("Enter marks of 3 subjects") Output:
for i in range(1,n+1): Enter number of students : 2
Enter marks of 3 subjects
◦ print("Enter student",i,"marks") Enter student 1 marks
◦ m1=int(input("Enter mark 1 :")) Enter mark 1 : 78
◦ m2=int(input("Enter mark 2 :")) Enter mark 2 : 89
◦ m3=int(input("Enter mark 3 :")) Enter mark 3 :79
Total : 246 Average : 82.0
◦ tot=m1+m2+m3 Enter student 2 marks
◦ avg=tot/3 Enter mark 1 :
◦ print("Total :",tot,"Average :",avg) 99
Enter mark 2 :
87
Enter mark 3 :
93
Total : 279 Average : 93.0
Noornilo Nafees 37
Definition of prime number:
◦ A natural number greater than one has not any other
divisors except 1 and itself. In other word we can say which
has only two divisors 1 and number itself.
◦ For example: 5. Their divisors are 1 and 5.
n=int(input("Enter a number to check whether it is a prime
number or not:"))
Output:
c=0
Enter a number to check whether it is a
for i in range(1,n+1): prime number or not:
◦ if(n%i==0): 7
◦ c=c+1 7 is a prime number
if(c==2):
◦ print(n,"is a prime number")
else:
◦ print(n,"is not a prime number")
Noornilo Nafees 38
Nested for loop:
Following is an example program to illustrate the use
Noornilo Nafees 39
Following is an example program to illustrate the use
of nested for loop to print the following pattern
11111
2222
333
44
5
for i in range(1,7):
◦ k=i+1
◦ for j in range(k,7):
print(i,end=‘\t’)
print(end=‘\n’)
Noornilo Nafees 40
Following is an example program to illustrate the use
of nested for loop to print the following pattern
1
22
333
4444
55555
666666
for i in range(1,7):
◦ k=i+1
◦ for j in range(1,k):
print(i,end=‘\t’)
print(end=‘\n’)
Noornilo Nafees 41
Following is an example program to illustrate the use
of nested for loop to print the following pattern
666666
55555
4444
333
22
1
for i in range(6,0,-1):
◦ for j in range(i,0,-1):
print(i,end=‘\t’)
print(end=‘\n’)
Noornilo Nafees 42
Following is an example program to illustrate the use
of nested for loop to print the following pattern
*
**
***
****
*****
******
for i in range(1,7):
◦ k=i+1
◦ for j in range(1,k):
print(“*”,end=‘\t’)
print(end=‘\n’)
Noornilo Nafees 43
Following is an example program to illustrate the use
of nested for loop to print the following pattern
******
*****
****
***
**
*
for i in range(6,0,-1):
◦ for j in range(i,0,-1):
print(“*”,end=‘\t’)
print(end=‘\n’)
Noornilo Nafees 44
Jump Statements in Python:
The jump statement in Python, is used to
unconditionally transfer the control from one part of
the program to another.
There are three keywords to achieve jump statements
in Python
(i)break statement,
(ii)continue statement,
(iii)pass statement.
Noornilo Nafees 45
(i)break statement: The break statement terminates
the loop containing it.
Control of the program flows to the statement
Noornilo Nafees 46
# Program to illustrate the use of break statement
inside for loop:
for i in “Jump Statement”:
◦ if i = = “e”:
break
print (i, end= ' ')
Output:
Jump Stat
Noornilo Nafees 47
(b) continue statement: Continue statement
terminates the current loop iteration & persist the loop
with next iteration.
# Program to illustrate the use of continue statement
◦ if word = = “e”:
◦ continue
◦ print (word, end = ' '
Output:
Jump Statmnt
Noornilo Nafees 48
(c) pass statement:
pass statement in Python programming is a null
statement.
pass statement when executed by the interpreter it is
completely ignored.
Nothing happens when pass is executed, it results in
no operation.
Noornilo Nafees 49
#Program to illustrate the use of pass statement
a=int (input(“Enter any number :”))
◦ if (a==0):
pass
◦ else:
print (“non zero value is accepted”)
Output:
Enter any number :3
non zero value is accepted
Noornilo Nafees 50
#Program to illustrate the use of pass statement
for val in “Computer”:
◦ pass
print (“End of the loop, loop structure will be built in
future”)
Output:
End of the loop, loop structure will be built in future.
Noornilo Nafees 51
Points to remember:
Programs consists of statements which are executed in
sequence, to alter the
flow we use control statements.
• A program statement that causes a jump of control from
one part of the program to another is called control
structure or control statement.
• Three types of flow of control are
o Sequencing
o Branching or Alternative
o Iteration
• In Python, branching is done using various forms of ‘if ’
structures.
• Indentation plays a vital role in Python programming, it is
the indentation that group statements no need to use {}.
Noornilo Nafees 52
Python Interpreter will throw error for all indentation
errors.
• To accept input at runtime, earlier versions of Python
Python.
• pass statement is a null statement, it is generally
Noornilo Nafees 53
Module 2 Quiz:
1. How many important control structures are there in
Python?
A) 3 B) 4
C) 5 D) 6
2. elif can be considered to be abbreviation of
A) nested if B) if..else
C) else if D) if..elif
3. What plays a vital role in Python programming?
A) Statements B) Control
C) Structure D) Indentation
4. Which statement is generally used as a placeholder?
A) continue B) break
C) pass D) goto
Noornilo Nafees 54
5. The condition in the if statement should be in the form of
A) Arithmetic or Relational expression
B) Arithmetic or Logical expression
C) Relational or Logical expression
D) Arithmetic
6. Which is the most comfortable loop?
A) do..while B) while
C) for D) if..elif
7. What is the output of the following snippet?
i=1
while True:
◦ if i%3 ==0:
break
◦ print(i,end='')
◦ i +=1
A) 12 B) 123
C) 1234 D) 124
Noornilo Nafees 55
8. What is the output of the following snippet?
T=1
while T:
◦ print(True)
◦ break
A) False B) True
C) 0 D) 1
9. Which amongst this is not a jump statement ?
A) for B) pass
C) continue D) break
10. Which punctuation should be used in the blank?
if <condition>_
◦ statements-block 1
else:
◦ statements-block 2
A) ; B) :
C) :: D) !
Noornilo Nafees 56
Hands on:
1. Write a program to check whether the given
Noornilo Nafees 57
2. Using if..else..elif statement check smallest of three
numbers.
print("Enter 3 number to find smallest of them :")
a=int(input()) Output:
b=int(input()) Enter 3 number to find
c=int(input()) smallest of them :
7
if((a<b)and(a<c)):
3
◦ print(a,"is smallest number") 6
elif(b<c): 3 is smallest number
◦ print(b,"is smallest number")
else:
Noornilo Nafees 58
Hands on:
3. Write a program to check if a number is Positive,
Negative or zero.
a=int(input("Enter a number to check whether it is positive
or negative or zero :"))
if(a>0):
◦ print(a,"is positive number")
elif(a<0):
◦ print(a,"is negative number")
elif(a==0):
◦ print(a,"is Zero")
Output:
Enter a number to check whether it is positive or negative
or zero :-3
-3 is negative number
Noornilo Nafees 59
4. Write a program to display
A
AB
ABC
ABCD
ABCDE
Noornilo Nafees 60
5. Fibonacci series using for loop
a=int(input("Enter the terms:"))
f=0 #first element of series
s=1 #second element of series
if (a<=0): Output :
◦ print("The requested series is",f) Please Enter the terms:
5
else:
0
◦ print(f,s,end=" ") 1
for x in range(2,a): 1
next=f+s 2
3
print(next,end=" ")
f=s
s=next
Noornilo Nafees 61
Number = int(input("\nPlease Enter the Range Number: "))
# Initializing First and Second Values of a Series
i=0 5. Fibonacci series using while loop
First_Value = 0
Second_Value = 1
Output :
# Find & Displaying Fibonacci series
Please Enter the Range
while(i < Number): Number: 5
◦ if(i <= 1): 0
Next = i 1
else: 1
Next = First_Value + Second_Value 2
3
First_Value = Second_Value
Second_Value = Next
print(Next)
i=i+1
Noornilo Nafees 62
6. Write a Python program TO ACCEPT A PERSON'S AGE AND CHECK
ELIGIBILITY TO VOTE USING SIMPLE if statement.
IF THE USER TYPE ANY NUMBER THAT ARE NOT BETWEEN 1 AND 5
THE PRINT NUMBER OUT OF RANGE
Noornilo Nafees 63
9. Write a Python program FOR THE FOLLOWING LOGIC.
GET THE AGE OF USER
(i). IF AGE IS BETWEEN 1 TO 12 THEN PRINT YOU ARE CHILD
(ii). IF AGE IS BETWEEN 13 TO 19 THEN PRINT YOU ARE IN
TEEN AGE
(iii). IF AGE IS BETWEEN 20 TO 45 THEN PRINT YOU ARE IN
YOUNG AGE
(iv). IF AGE IS MORE THAN 45 THEN PRINT YOU ARE IN OLD
AGE
10. Write a Python program TO FIND GREATEST OF THREE
NUMBERS
11. Write a Python program TO FIND GREATEST OF THREE
NUMBERS USING CONDITIONAL/TERNARY OPERATOR
12. Write a C program to display even numbers from 80 to
70 using while loop
Noornilo Nafees 64