CH 6 FLOW OF CONTROL+code
CH 6 FLOW OF CONTROL+code
FLOW OF CONTROL
Generally, a program executes from beginning to end. Some
programs do not execute in order. As per the requirements, execution order of the program can be
changed and it is also possible to execute a program repeatedly.
Python provides control structures to manage the order of
execution of a program, which are if-else, for, while and jump statements like break and continue.
Types of Statements
There are three types of Statements provided by Python.
❖ Empty Statement(pass)
❖ Simple Statement
❖ Compound Statement
Statements are the instruction given to the computer to perform any kind of action, be it data
movements, making decisions or repeating actions.
Simple Statement
Any single executable statement is a simple statement in Python.
Eg. name=str(input(“Enter your name:”))
Compound Statement
A Compound Statement represents a group of statements executed as a unit. In Python, Compound
Statements have headers ending in colon, and a body containing a set of statements to be executed.
Eg. if x>y:
print(x)
1. Sequential
The statements will be executed sequentially (one after the other), which represents the default flow
of control. It is the normal flow of control in a program, where Python program begins with the first
statement, followed by the second, till the final statement of the program is executed. Sequence
Statement Flow is the simplest flow of control.
Statement 1
Statement 2
Statement 3
2. Selective
The Selection construct was a condition test to determine the execution of statements. If a condition
is True, a set -of -statements is followed. Otherwise, a different set of statements is followed. This
construct is also called decision construct because it helps in making a decision about which set- of -
statements is to be executed.
TRUE FALSE
Condition?
Statement 1 Statement 3
Statement 2 Statement 4
3. Iterative (Looping)
The iteration construct means repetition of a set – of – statements depending upon a condition test.
The statement gets executed till the time a condition is True. As soon as the condition becomes
False, the repetition stops.
TRUE FALSE
Condition?
Once False, the loop will exit
Statement 1
Statement 2
if-Statement
It is also called Selection Construct. The if statement selects a particular condition, if the
condition evaluates to True, a course of action is followed i.e. a set of statements are executed.
Otherwise, another set of statements gets executed.
Syntax:
if<conditional expression>:
Statement
Eg. ch=input (“Enter a single character:”)
If ch==’ ‘:
print (“You entered a space”)
if ch>=’0’ and ch<=’9’:
print (“Entered character is a digit”)
if-else Statement
The if-else statement tests a condition. If the condition evaluates to True, a set of instructions will be
executed, and if it evaluates to False, another set of instructions are executed.
Syntax:
if<conditional expression>:
Statement
else:
Statement
Eg. if a>0:
else:
num=int(input(“Enter an integer:”))
if num%2==0:
else:
Q 2. Write a program to compare three numbers and give the largest of the three.
max=x
if y>max:
max=y
if z>max:
max=z
2-Calculate Perimeter”””)
if ch==1:
area=22/7*radius*radius
else:
perm=2*22/7*radius
if-elif Statement
It is the short form of else-if statement. If the previous conditions were not True, then do this condition.
Syntax:
if<conditional expression>:
Statement
elif<conditional expression>:
Statement
elif<conditional expression>:
Statement
else:
Statement
Q. Write a program to calculate the absolute value of a number or an integer using if-elif conditional
statement.
if num>=0:
elif num<0:
op=input(“Enter operator[+-*/%]:”)
if op==’+’:
result=num1+num2
elif op==’-‘:
result=num1-num2
elif op==’*’:
result=num1*num2
elif op==’/’:
result=num1/num2
elif op==’%’:
result=num1%num2
else:
print(“Invalid operator!”)
print(num1,op,num2,’=’,result)
Nested if Statement
The nested if-else statement allows you to check for multiple text expressions and execute different codes for
more than two conditions.
Syntax:
if <conditional expression>:
Statement
else:
Statement
Statement
else:
Statement
Q. Program that reads three numbers(integers and print them in ascending order.
min=mid=max=None
if num2< num3:
else:
if num1< num3:
else:
else:
if num1< num2:
else:
Range () function
The range() function of Python is used with the for loop. It generates a list which is a special
sequence type. A sequence in Python is a group of values bounded by a single name.
The common use of range () is in the form: range (<lower limit>,<upper limit>) or range (l,u) ,
where l and u being integers
The above range function will produce a list having values starting from l, (l+1), (l+2),……(u-2),(u-1)
An empty list has no numbers falling in the arithmetic progression.
Eg: range(5,0) gives[ ] (an empty list)
The range function with different step value should use the following syntax: range(<lower
limit,<upper limit>,<step value>) or range(l,u,s)
This will produce a list having values:l,l+s,l+2s……<=(u-s)
Q. Give the values generated for the following:
Output:
1
1
4
16
7
49
Q. Write a program to print multiplication table of any number.
for i in range(1,11):
print(num’x’,i,’=’,num*i)
Q. Write a program to print sum of natural numbers between 1 and 5.Print the sum progressively, i.e., after
adding each natural number, print sum so far.
sum=0
for i in range(1,6):
sum+=i
Output
sum=0
for i in range(1,6):
sum+=i
Output:
Note : The value of the loop variable after the for loop is over, is the highest value of the list.
2. while loop
A while loop is a conditional loop that will repeat the instructions Flowchart:
loop-body
➢ The loop body may contain a single, multiple or an empty statement.
➢ The loop repeats until the condition becomes false. When the condition
becomes false, the control passes to the next line after the loop body.
Eg. a=5
while a>0:
print(“a=”,a)
a=a-3
print(“loop over!”)
Output:
a=5
a=2
loop over!
Note: The variable used in the condition of while loop must have the same value before entering into the while
loop.
❖ In a while loop, a loop control variable should be initialized. This must be done before the loop begins
as an uninitialized variable cannot be used in a test expression.
❖ The loop variable must be updated inside the body of the loop. If the test condition does not become
false, the loop will result in an endless loop or an infinite loop.
a=5
while a>0:
print(a)
print(“Loop over!”)
The above loop is an infinite loop as the value of ‘a’ remains 5 and the test condition a>0
remains true always. In this case ‘break’ statements help to break the loop.
Q. Write a program to calculate the factorial of a number.
num=int(input(“Enter a number:”))
fact=1
a=1
while a<=num:
fact*=a
a+=1
Output:
Enter a number: 3
The factorial of 3 is 6
Q. Write a program to calculate and print the sums of the even and odd integers of the first ‘n’ natural
numbers.
a=1
sumE=sumO=0
while a<=n:
if a%2==0:
sumE+=a
else:
sumO+=a
a+=1
Output:
➢ Break
➢ Continue
1.Break Statement:-The break statement enables a program to skip over a part of the code. A break
statement terminates the very loop it lies within. Execution resumes at the statement immediately following
the body of the terminated statement.
Syntax: Flowchart:
Eg.
In while loop In for loop
i=1 language=[‘java’,’python’,’c++’]
while i<6: for x in language:
print(i) if x==’python’:
i+=1 break
if i==3: print(x)
break
Output: Output:
1 python
2
Note: If the break statement appears in a nested loop, then it will terminate the very loop it is in. If the break
statement is inside the inner loop, then it will terminate the inner loop only and the outer loop will continue as
it is.
2.Continue Statement:-With the continue statement we can stop the current location and continue with the
next iteration.
Syntax:
Eg.
Syntax:
print(i) 2
else: 3
num=int(input(“Enter a number:”))
N=int(num/2)
for i in range(2,N+1):
R=num%i
if R==0:
print(num,”is a composite number”)
break
else:
Nested loops
A loop may contain another loop in its body. This form of a loop is called nested loop.But in a nested loop, the
inner loop must terminate before the outer loop.
Syntax:
**
***
****
12345
1234
123
12
1
n=int(input(“Enter the no. of rows=”))
for i in range(n,0,-1):
for j in range(1,i+1):
print(j,end=” “)
print()
num=int(input("Enter a number="))
num1=num
n=len(str(num))
sum=0
while num>0:
digit=num%10
num=num//10
sum+=digit**n
if sum==num1:
print(num1,"is an Armstrong number")
else:
print(num1,"is not an Armstrong number")
Q. Program to determine whether a number is Palindrome or not.
num = int(input("Enter an integer (>1000): "))
num1=num
reverse=0
while num>0:
digit=num%10
num=num//10
reverse=reverse*10+digit
if num1==reverse:
print(num1,"is a Palindrome")
else:
print(num1,"is not a Palindrome")
Q. Program to input two numbers and print their LCM and HCF.
else:
print(num,"is not a perfect number")
Q. Program to find the sum of the series 1+x+x2+x3…..+xn
Q. Write a program that takes the name and age of the user as input and displays a
message whether the user is eligible to apply for a driving license or not. (the
eligible age is 18 years).
name = input("Enter your name: ")
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to apply for a driving license.")
else:
print(“Not eligible to apply for a driving license.")
Q. Write a program to find the grade of a student when grades are allocated as
given in the table below. Percentage of the marks obtained by the student is input
to the program.
n = float(input('Enter the percentage of the student: '))
if(n > 90):
print("Grade A")
elif(n > 80):
print("Grade B")
elif(n > 70):
print("Grade C")
elif(n >= 60):
print("Grade D")
else:
print("Grade E")
*********************************