0% found this document useful (0 votes)
10 views

Chapter 4 Flow of Control IP-updated

Uploaded by

Mysha Shaikh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Chapter 4 Flow of Control IP-updated

Uploaded by

Mysha Shaikh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

CHAPTER 4- FLOW OF CONTROL

Learning Objective:

After Having Studied this Chapter, You will be able to Understand : -

 Computational Thinking.
 Algorithms, Flowcharts, Pseudocodes and Decision Tree.
 The Control Flow-Sequence, Selection and Iteration.
 If el if in Python.
 For Range and While Loop.
 Nested loops.

4.9 FLOW OF CONTROL- INTRODUCTION


A program’s control flow is the order in which the program’s code executes.

The normal flow of execution of statements in a program is sequential i.e. each


statement is executed in the order of its appearance in the program. However
depending upon the requirement of a problem, it is often required to alter the normal
sequential execution which means that programmer may desire to selectively or
repeatedly execute a segment of a program. The control flow of a Python program is
regulated by conditional statements, loops, and function calls. This chapter covers
if statement, for, while and nested loops.
4.10 THE FLOW CONTROL

Control Structure refers to the program segment which controls the flow of program
execution. In any programming language, there are 3 control structures: Sequence,
Selection and Iteration.

4.10.1 SEQUENCE

Sequence refers to the execution when statements are executed one after another.
This construct specifies the normal flow of control in a program in which all the
statements are executed as they appear. This represents the default flow of execution.
So far whichever lines of coding you have written represent sequence flow of control.

4.10.2 SELECTION

Selection refers to execution of a set of statement depending on a condition. If


condition is true, one set of statements is executed otherwise another set of statement
will be executed. This control structure is controlled by conditional statement or decision
construct as it helps in making decision on a course of action.

4.10.3 ITERATION
Iteration refers to repeated execution of a set of statement depending on a condition.
Till the time a particular condition is true, a set of statements are repeated again and
again. As soon as the condition becomes False, the repetition stops. Iterative control
structure is controlled by looping statement.

4.11 THE IF AND ELIF STATEMENT

Often, you need to execute some statements only if some condition holds, or choose
statements to execute depending on several mutually exclusive conditions. The Python
compound statement if, which uses if, elif, and else clauses, lets you conditionally
execute blocks of statements. Here’s the syntax for the if statement:

if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)

The elif and else clauses are optional. Note that unlike some languages, Python does
not have a switch statement, so you must use if, elif, and else for all conditional
processing.

Here’s a typical if statement:

if x < 0: print "x is negative"

elif x % 2: print "x is positive and odd"

else: print "x is even and non-negative"

When there are multiple statements in a clause (i.e., the clause controls a block of
statements), the statements are separated using different indents.

If the expression for the if clause evaluates as true, the statements following
the if clause execute, and the entire if statement ends. Otherwise, the expressions for
any elif clauses are evaluated in order. The statements following the first elif clause
whose condition is true, if any, are executed, and the entire if statement ends.
Otherwise, if an else clause exists, the statements following it are executed.

4.12 PYTHON NESTED IF STATEMENTS


We can have a if...elif...else statement inside another if...elif...else statement. This is
called nesting in computer programming.

Any number of these statements can be nested inside one another. Indentation is the
only way to figure out the level of nesting. This can get confusing, so must be avoided if
we can.

# In this program, we input a number and check if the number is


positive or negative or zero and display an appropriate message
using nested if.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

4.14 SOLVED PROGRAMS USING IF ELIF

1. WAPS (Write a python script) to accept a number and check if it is positive


or negative.

Solution:

a=int(input("enter a number"))

if a>0:

print(a,"is positive")

else:

print(a,"is negative")

2. WAPS (Write a python script) to accept a number and check if it is positive


negative or zero.

Solution:

a=float(input("enter a number "))

if a>0:

print("it is positive")

elif a<0:

print("it is negative")

else:
print("the number is 0")

3. WAPS (Write a Python Script) to accept the Physics, Chemistry and


Mathematics and Computer marks of a student. Calculate
percentage. (Assume marks are out of 100.)

display the remarks accordingly.

Percentage Grade

> 90 Outstanding

81 to 90 High Achiever

71 to 80 Good

< 70 Average

Solution:

a=int(input("Please enter the maths marks"))

b=int(input("Please enter the chemistry marks"))

c=int(input("Please enter the physics marks"))

d=int(input("Please enter the computers marks"))

av=(a+b+c+d)/4

if av>90:

print("Outstanding")

elif av>80 and av<=90:


print("High Achiever")

elif av>70 and av<=80:

print("Good")

else:

print("Average")

4. WAPS (Write a Python Script) to create a menu as shown below


and perform the various operations based on user’s response

Print(“MAIN MENU”)
print-------------------------------------------------
print(“1. Area of Right angled Triangle “)
2. Area and Perimeter of a Square
3. Area and Perimeter of a Circle
Choice=int(input(“”))
If choice==1:
Area=
Print(area)
Elif choice==2:
Area
Perimeter

Solution:

print("1 for Area of a right angle Triangle")

print("2 for Area and Perimeter of square")

print("3 for Area and Perimeter of circle")

print("4 Invalid Choice")

ch=input("Enter your choice")


if ch==1:

l=int (input("Enter the length"))

b=int (input("Enter the base"))

a=0.5*l*b

print(“the area is “, a)

elif ch==2:

s=int (input("Enter the side"))

a=s*s

p=4*s

print(“The area and perimeter is “, a,p)

elif ch==3:

r=int (input("Enter the radius"))

a=3.14*r*r

p=2*3.14*r

print(3.14*r*r)

else:

print(“invalid choice”)

5. Wedding Planner shop calculates salary of each salesman


according to the sale done by them. WAPS to accept the sales
amount and display the net amount according to the following
discount table.

Sales Bonus DA

If Sales > 50000 A=40% of Sales 2000

Net=sales+A+DA
Print(net)

Sales between 40001 to 50000 30% of Sales 1500

Sales between 30001 to 40000 20% of Sales 1000

Sales between 20001 to 30000 15% of Sales 500

Sales <= 20000 05% of Sales 200

Net = Sales + Bonus + DA

Solution:

a=int(input("enter a sales "))

if a>50000:

b=.4*a

n=a+b+2000

elif a>=40001 and a<=50000:

b=.3*a

n=a+b+1500

elif a>=30001 and a<=40000:

b=.2*a

n=a+b+1000

elif a>=20001 and a<=30000:

b=.15*a

n=a+b+500

else:

b=.05*a
n=a+b+200

print(n,"is the net amount")

6. WAPS (Write a Python Script) to check if the entered number is a leap


year or not.

Solution:

a=int(input("enter a 4 digit number "))

if a%100==0 and a%400==0:

print("it is leap year")

elif a%4==0:

print("it is a leap year")

else:

print("it is not leap year")

7. Accept three numbers. Find the sum and the sum of non
duplicate numbers(Eg: sum of 3, 3, 6
=12;
Sum of Non duplicate numbers of 3, 3, 6=6)
Solution:

a=int(input("Enter a"))

b=int(input("Enter b"))

c=int(input("Enter c"))

if a==b:

print(“the sum is “, c)

elif b==c:

print((“the sum is “, a)
elif a==c:

print((“the sum is “, b)

elif a==b and a==c:

print((“the sum is “, 0)

else:

print((“the sum is “, a+b+c)

print((“the sum of all numbers is “, a+b+c)

8. WAPS to accept 3 numbers and find the largest number among


them.

9. WAPS (Write a Python Script) to find the max,mid and min from
from three numbers.
Solution:

a=int(input("Enter a"))

b=int(input("Enter b"))

c=int(input("Enter c"))

if a>b and a>c and b>c:

o=a, b, c

elif b>c and b>a and a>c:

o=b, a, c

elif c>a and c>b and a>b:

o=c, a, b

elif c>a and c>b and b>a:

o=c, b, a

elif b>a and b>c and c<a:


o=b, c, a

else:

o=a,c, b

print("Descending order is,", o)

10. WAPS to accept a character and check if it is uppercase


character, lowercase character or digit or special character

Solution :

q=input("Enter a character")

if q>='A' and q<='Z':

print("Capital")

elif q>='a' and q<='z':

print("Not capital")

elif q>'0':

print("Digit")

else:

print("Special character")

11. Write a menu driven program for the following (not in


syllabus)
MAIN MENU
-------------------------------------------------
1. (a+b )2+(a-b)2
2. √ a+ √ b
3. √ a3+b3+c3

Solution :

import math

print("MAIN MENU")

print("-----------------------------------------")

a=int(input("Enter a"))

b=int(input("Enter b"))

c=int(input("Enter c"))

x=math.pow((a+b),2) + math.pow((a-b),2)

y=math.sqrt(a) + math.sqrt(b)

z=math.sqrt(math.pow(a,3) + math.pow(b,3) + math.pow(c,3))

print(x)

print(y)

print(z)

12. WAP to accept a number and round off to the bigger value
using ceil( ) function and round off to the lower value using
floor( ) function(hint: import math )( not in syllabus)
Solution:

import math

a=float(input("Enter a"))

r1=math.ceil(a)

r2=math.floor(a)

print("The higher value is", r1)


print("The lower value is", r2)

4.15 UNSOLVED PROGRAMS USING IF ELIF


1. Write a program to check if the number entered is even or odd.
2. Write a program to print the square if the number entered is even,
otherwise print its cube.
3. Accept a day(Sunday, Monday..)If the entered day is Saturday or
Sunday display “Holiday” otherwise “Working day”
4. Write a program to accept the 2 sides of a rectangle and display if
its area is greater than its perimeter.
5. Write a program to print the largest of three numbers.
6. Write the code to accept three marks and find the sum of best two.
7. WAP check whether entered char is a vowel or consonant.
8. Welcome shop deals in purses and belts.WAPS to accept item and amount from
the user and calculate total amount to be paid. GST is added according to the
below table.
Item GST rate
BELT<=500 5%
BELT>500 18%
PURSE<=1000 5%
PURSE>1000 12%

4.16 RANGE FUNCTION IN PYTHON


The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.

Syntax
range(start, stop, step)
Parameter Description

Start Optional. An integer number specifying at


which position to start. Default is 0

Stop Optional. An integer number specifying at


which position to end.

Step Optional. An integer number specifying


the increment. Default is 1

Let’s understand range with the help of the examples given below.

Example:
Range (0,5):This will generate numbers 0,1,2,3,4.
Range(x,y): This will generate numbers x,x+1…..y-1.
Range (2, 8, 2): This will generate numbers 2, 4, 6.
Range (8, 3,-1): This will generate numbers 8, 7,6,5,4.

4.17 IN and NOT IN OPERATOR:

IN and NOT IN are membership operators. The ‘in’ operator is used to check if
a value exists in a sequence or not. Evaluates to true if it finds a variable in the
specified sequence and false otherwise.
>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

4.18 FOR LOOP IN PYTHON


For loop in python is used to repeat certain statements in Python.
A for loop is used for iterating over a sequence.
Let’s understand For Loop with the help of an example.

for x in range(0,6):
print(x)
output will be
0
1
2
3
4
5
Notice that 6 is not included in the list.

The above loop will be processed as follows.


a) First the loop variable which is x, is given the initial value of the list, i.e., 0 and the
statements in the body of the loop will be executed. Hence 0 will be printed.
b) Then the loop variable will be assigned the next the value in the list, i.e., 1 and the
statements in the body of the loop will be executed. Hence 1 will be printed. This above
procedure will repeat for 2, 3, 4 and 5.
c) When the value of x becomes 6, the loop ends and hence 6 is not printed.

4.19 FOR RANGE-SOME SOLVED EXAMPLES

1. WAPS to print “Computer Science” 4 times.

Solution: Output
for a in range(1,5): Computer Science
print("Computer Science") Computer Science
Computer Science
Computer Science
2. WAPS to print first 5 natural numbers.

Solution: Output
for a in range(1,6): 1
2
print(a)
3
4
5
3. WAPS to print numbers between 6 and 10.

Solution: Output
for a in range(6,11): 6
7
print(a)
8
9
10
4. WAPS to print odd numbers between 1 and n.(include
n)

Solution: Output
enter the value of n : 5
n=int(input("enter the value 1
3
of n : "))
5
for i in range(1,n+1,2):
print(i)

5. WAPS to print even numbers between 1 and n.(include


n)

Solution: Output
enter the value of n : 5
n=int(input("enter the value 2
4
of n : "))
for i in range(2,n+1,2):
print(i)

6. WAPS to print even numbers in reverse between 8 and


n.n is not included.

Solution: Output
enter the value of n : 1
n=int(input("enter the value 8
6
of n : "))
4
for i in range(8,n,-2): 2
print(i)

7. WAPS to print numbers in reverse between 8 and n.n


is included.

Solution: Output
enter the value of n : 4
n=int(input("enter the value 8
7
of n : "))
6
for i in range(8,n+1,-1):
print(i)

8. WAPS to print the multiplication table of 7 a


number.

Solution: Output
enter the value of n : 5
n=int(input("enter the value 5*1=5
5*2=10
of n\n"))
5*3=15
5*4=20
for i in range(1,11): 5*5=25
5*6=30
print(n," * ",i,"= ",i*n)
5*7=35
5*8=40
5*9=45
5*10=50

9. WAPS to find the sum of first n natural numbers


1+2=3
Solution: Output
s=0 enter the value of n : 5
n=int(input("enter the value 15
of n : "))
for i in range(1,n+1):
s=s+i
print(s)

9. WAPS to accept any 5 numbers and find their sum.

Solution: Output
enter the value of n : 5
S=0 enter the value of n : 34
for i in range(1,6): enter the value of n : 23
n=int(input("enter the enter the value of n : 23
value of n : ")) enter the value of n : 67
s=s+n 152
print(s)
11. WAPS to display first n terms of fibonecci series.
(Where every third term is the sum of previous two.)
0 1 1 2 3 5 8 ….n
a b c
a b c
Solution: Output
n=int(input("enter a enter a number10
0
number"))
1
a=0 1
2
b=1
3
print(a) 5
8
print(b)
13
for i in range(3,n+1): 21
34
c=a+b
fibonacci series printed
print(c)
a=b
b=c
else:
print("fibonacci series
printed")

12. WAPS to find the factorial of a number. Example 5!


=120

Solution: Output
f=1 enter n : 5
120
n=int(input("enter n : "))
for i in range(1,n+1):
f=f*i
print(f)
14. WAPS find the factors of a number.

Solution: Output
n=int(input("enter a number
: enter a number : 24
1 is factor
"))
2 is factor
for i in range(1,n+1): 3 is factor
4 is factor
if n%i==0:
6 is factor
print(i, “ is factor”) 8 is factor
12 is factor
24 is factor

15. WAPS to check if the entered number is prime or


not.

Solution: Output
count=0 enter a number : 23
n=int(input("enter a number : prime
"))
for i in range(1,n+1):
if n%i==0:
count=count+1
if count==2:
print("prime")
else:
print("non prime")

16. WAPS to find LCM and GCD of two entered numbers

Solution: Output
a=int(input("enter first enter first number6
enter second number24
number"))
gcd is 6
b=int(input("enter second lcm is 24.0
number"))
if a<b:
lower=a
else:
lower=b
for i in range(1,lower+1):
if a%i==0 and b%i==0:
g=i
l=a*b/g
print("gcd is ",g)
print("lcm is ",l)

17. WAPS to check if entered number is perfect or not.


N 6
1 for I in range(1,n)
2 n%i==0
3 sum=sum+i
2
3 if sum==n
4

Solution: Output
count=0 Enter a number: 6
Perfect
n=int(input("enter a number :
"))
for i in range(1,n):
if n%i==0:
sum=sum+i
if sum==n:
print("perfect")
else:
print("non perfect")

18. WAP to display the first 10 Mersenne numbers . (Numbers


in the form 2n-1 are called Mersenne numbers. (21-1 =1 , 22-1
=3 , 23 -1=7 ….)

Solution: Output
for a in range(1,11): 1 3 7 15 31 63 127 255 511
1023
mersnum=2**a-1
print(mersnum,end=” “)
print()

19. WAPS to find the largest number in the list of n


entered numbers.
Solution: Output
max=0 enter the number of
numbers6
n=int(input("enter the
enter the number12
number of numbers")) enter the number67
enter the number2
for i in range(1,n+1):
enter the number78
a=int(input("enter the enter the number12
enter the number54
number"))
78
if a>max: >>>
max=a
print(max)

20 WAPS to accept n numbers and find the count of even


and odd numbers from them.

Solution: Output
ce=0 Enter number of numbers: 6
Enter a number : 23
co=0 Enter a number : 24
Enter a number : 22
n=int(input("enter the number of numbers")) Enter a number : 35
Enter a number : 25
for i in range(1,n+1): Enter a number : 26
Count of even numbers
a=int(input("enter the number")) is :3
Count of odd numbers is :3
if a%2==0:

ce=ce+1

else:

co=co+1
print("the count of even numbers is ", ce)

print("the count of odd numbers is ", co)

21 WAPS to display sum of even and sum of odd numbers


between m and n.

se=0
so=0 Output
m=int(input("enter first
enter first number2
number"))
enter second number22
n=int(input("enter second the sum of even
numbers is 132
number"))
the sum of odd numbers is
for i in range(m,n+1): 120
if i%2==0:
se=se+i
else:
so=so+i
print("the sum of even
numbers is ",se)
print("the sum of odd numbers is
",so)

4.25 SOLVED QUESTIONS

1. Give the looping statement to generate the following series.

1, 4, 9, 16, 25, 36,49, 81 100

Ans for i in range (1,11):

print(i*i,end=’ ‘)

2. Give the looping statement to generate the following series.


1,4,7,3,12,21……..15 terms

Ans a,b,c=1,4,7

for i in range (1,6):

print(a, b, c,end=' ')

a=a*3

b=b*3

c=c*3

7. for i in range(100,29,-10):

print(i,end=' ')

print(i)

Ans 100 90 80 70 60 50 40 30 30

11 Correct the errors in the following code. Underline each correction.


w = “Raining”
if w = “sunny” :
print(“Wear Sun Block’)
elif w= “snow”:
print(“Going Skiing”)
else:
print(Weather)

Ans w = "Raining"

if w == "sunny" :

print("Wear Sun Block")

elif w== "snow":

print("Going Skiing")

else:

print("Weather")

13 Write the output of the following code:


v=5
if(v+5==11):
print((v+5==11)+1)
else:
print((v+5==11)+2)
print(v+5<=10)

Ans 2

True
17. Give the output

x=30

if x>30:

print("hi")

elif x>20:

print("hello")

print("bye")

Ans Hello

Bye

Try these Questions


1. What is the output produced by the following code?
x=1

if x>3:

if x>4:

print (“A”, end=’ ‘)

else:

print (“B”, end=’ ‘)


elif x<2:

if(x!=0):

print (“C”, end=’ ‘)

print (“D”)

2. What is the following code doing? What would it print for input as 3?
n=int (input(“Enter an integer:”))

if n<1:

print(“invalid value”)

else:

for i in range(1, n+1):

print(i*i)

7. Write a short program to print the following series:


i. 1 4 7 10 . . . . . 40
ii. 1 -4 7 -10 . . . . . . -40

8. Write a program to input 3 sides of a triangle and print whether it is an


equilateral, scalene or isosceles triangle.

9. Write a short program to find largest number of a list of numbers entered


through keyboard.
print("Enter numbers:")
print("(Enter 'q' to see the result)")
l = input()
if l != 'q' and l != 'Q' :
l = int(l)
while True:
n = input()
if n == 'q' or n == 'Q' :
break
n = int(n)
if n > l :
l=n
print("Largest Number =", l)
10. Write a program to input N numbers and then print the second largest
number.
11. Write Python programs to sum the given sentences:
a) 2/9 – 5/3 + 8/17……… (print 7 terms)
b) 12 + 32 + 52 + ……… + n2 (input n)
Unsolved Theory Questions.

You might also like