[go: up one dir, main page]

0% found this document useful (0 votes)
434 views66 pages

Chapter-9 - Flow of Control

Uploaded by

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

Chapter-9 - Flow of Control

Uploaded by

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

9

Flow of
Control

In Tis Chapter

9.1 Introduction 9.5 Repetition of Tasks- A Necessity


9.2 Types of Statements in Python 9.6 The Range() Function

9.3 Statement Flow Control 9.7 Iteration/ Looping Statements

9.4 The if Statements of Python

9.1 INTRODUCTION
Generally a program executes its statements from beginning to end. But not many programs
execute all their statements in strict order from beginning to end. Programs, depending upon
the need, can choose to execute one of the available alternatives or even repeat a set of
statements. To perform their manipulative miracles, programs need tools for performing
repetitive actions and for making decisions. Python, of course, provides such tools by providing
statements to attain so. Such statements are called program control statements. This chapter
selection statement if and later iteration
discusses such statements in details. Firstly,
statements for and while are discussed.
This chapter also discusses some jump statements of Python which are break and continue.

.2 TYPES OF STATEMENTS IN PYTHON


to pertorm any kind of action, be it data
Statements the instructions given to the computer
are
be it repeafing actions. Statements form the smallest
movements, and be it making decisions or
executable unit within a Python program. Python statements can belong to one of the following

three types
Empty Statement
Simple Statement (Single statement)
Compound Statement
271
272 COMPUTER SCIENCE WITH
PYTHON.
1. Empty Statement (Null Statement) As you can make out that
simple
The simplest statement is the empty statement single
i.e., a statement which does nothing. In Python:3. Compound Statement
are line statements.
statements
an empty statementis pass statement. It takes
the following form:
A compound statement represents
sents agroup
NOTE statements executed as a unit. The
pass statements of
coPof
The pass statement of Python hon
are written
in mpoun
as
Wherever Python is a do nothing statement i.e., pattern as shown below:
encounters a pass empty statement or null <compound statement header>
statement, Python operation statement <indented body containing
does nothing and moves to next statement in : simple and/or compound multiplel
the flow of control. statements
That is, a compound statement
A pass statement is useful in those has:
instances: a header line which
where the syntax of the language
requires begins
keyword and ends with a colon. with a
the presence of a statement but where the
:
logic of the program does not. We will see it a body consisting of one
or more Python
in loops and their bodies. statements, each indented inside
the
header line. All statements in the
2. Simple Statement at the same level of
body are
indentation.
Any single executable statement is a
simple You'll learn about some other compound
statement in Python. For example, following is
statements (if, for, while) in this
a
simple statement in Python: chapter.
name input ( "Your name" NOTE
Another example of simple statement is A compound statement in Python has a header
ending
with a colon (: ) and a body containing a sequence of
print (name) # print function called
statements at the same level of indentation.

9.3 STATEMENT FLOW CONTROL


In a program, statements
may be executed sequentially,
selectively or iteratively. Every programming
language provides constructs to support sequence, selection or iteration.
Let us discuss what is meant
by sequence, selection or iteration constructs. Statement 1
Sequence
The sequence construct means the statements
sequentially. This represents the default flow of statementbeing
are executed Statement 2
(see Fig. 9.1).
Every Python program begins with the first statement of program. Each Statement3
statement in turn is executed
(sequence construct). When the final
statement of program is executed, the program is done.
the normal flow of control in a Sequence refers to
program and is the simplest one. Figure 9.1 The sequence
Selection construct.

The selection construct means the execution of


a
statement(s) depending upon a conaitohe
condition evaluates to True, a course-of-action (a set of
statements) is followed
course-of-action (a different set of statements) if followed. This construct otherwi h is
also called decision construct because it helps in
(selection co1>
making
decision about which set-of-stae
is to be executed.
1. Conventionally, Python uses four spaces to move to next level of indentation.
Chopter:FLOWO
OF CONTROL
FLOW
9:
273

Adiacent figure (Fig. 9.2) explains


Adjace One course-of-action
selection construct.
True
Condition ?
Statement 1 Statement2|
You apply decision-making or
False
election in your
real life so many times
R, if the trattic signal light is red, then
the
top; if the traffic signal light is yellow Statement 1
then wait; and if the signal light is
green then go. Statement 2
You can think of many such real life
examples of selection/decision-making.
Figure 9.2 The selection construct.
epetition lieration (Looping)
The iteration constructs mean repetition

of a set-of-statements depending upon a


Condition ? False
condition-test. Till the time a condition is The exit
True (or False depending upon the condition
True
loop), a set-of-statements are repeated
again and again. As soon as the Statement 1
condition becomes False (or True), the The loop body
repetition stops. The iteration construct
is also called looping construct. Statement 2

The adjacent figure (Fig. 9.3) illustrates


an iteration construct. Figure 9.3 The iteration/repetition construct.

The set-of-statements that are repeated again and again is called the body of the loop. The
condition on which the execution or exit of the loop depends is called the exit condition or
test-condition.
You can find many examples of iteration or looping around you. For instance, you often see
your mother cook chapatis or dosas or appams tor you.

Repeat the adjacent process (steps (), Let's see, what sh e does for it:
, (i) for (i) put rolled chapati or dosa batter on flat pan or tawa
This is
next
chapati/dosa/appam.
looping or iteration. (ii) turn it 2-3 times (iii) once done take it off.
You can find numerous other examples of repetitive work in your real life e.g., washing clothes;
colouring in colouring book etc. etc.
C h e c k P o i n t

Every programming language must support these three


types of constructs as the sequential program execution (the
9.1 default mode) is inadequate to the problems we must solve.
.What is a statement ? How many types
Or
Python also provides statements that support these
statements are there in Python ? constructs. Coming sections discuss these Python
2.
What is the statements - if that supports selection and for and while
of a pass significance
statement? that support iteration. Using these statements you can
What is a compound statement ? Give create programs as per your need.
Cample of a compound statement.
But before we talk about these statements, you should
What are the three
constructs that know basic tools that will help you decide about the logic to
govern statement flow?
solve a given problem i.e., the algorithm. For this, there are
What is the need for selection and multiple tools available.
loopingconstructs
274 COMPUTER SCIENCE WITH
In the following section, we are going to talk about three such tools - Flowcharhs
PYTHON
vcharts,
and pseudocode.
decision tre
9.4 THE if STATEMENTS OF PYTHON
The if statements are the conditional statements in Pythorn and these implemo
constructs (decision constructs). mplement seleg
An if statement tests a
particular condition; if the condition evaluates to true, a cour
is followed i.e., a statement or set-of-statements is executed. rse-of-
evaluates to false), the course-of-action is wise (if(it the
Otherwise the on
ignored. condition
Before we proceed, it is that
important you recall what you learnt in Chapter 8 in
and logical operators as all that will
help you form conditionals in this chapter, Al relati
,

note in all forms of


if statement, we are using true to refer to Boolean value True as well ar
value true toal Collectively
; similarly, false here will refer to Boolean value False and truthal.
S truth

false tual Collectively. value

9.4.1 The if Statement


The simplest form of statement tests
if a condition and if the condition
evaluates
carries out some instructions and does to tre it
nothing in case condition evaluates to false.
The if statement is a compound statement and its
syntax (general form) is as shown below:
if <conditional expression> :

statement
The statements inside an if are
[statements] indented at same leve.
where a statement
may consist of a
single statement, a compound statement, or just the pass
statement (in case of
empty statement).
Carefully look at the if statement it is also
; a
compound statement having a header and a bo
containing indented statements. For instance, consider the following code
The header of
fragment
if statement; notice
Conditional i fch =='' colon (:) at the end
expression
spaces+=1
Body of if. Notice that all the statements
chars+1 | in the
if-body are indented at sanme level
In an
if statement, if the conditional
the statements in the expression evaluates to true,
body-of-if are executed, otherwise ignored. NOTE
The above code will check
whether the character Python is vey
stores a space or not ; if it variable ch Indentation in
does (i.e., the condition important when you are using
evaluates to true), the number of ch==' '

compound statement. Maxe

and number of characters spaces are incremented


by 1 Sure to indent all statements
incremented by value 1.
(stored in variable
chars) are also leve.
one block at the same

To see If, however, variable ch does not store ch==" "evaluate: to


if Statement a
false, then space i.e., the condition
in action nothing will
happen; no
statenment from the
ch= be executed
Consider another example
illustrating the use of if
body-of-f will
ch input ( "Enter a
single
statement:
if ch >= 'd and ch <='9: character:")
print ("You entered a digit.")
clenter9:
FLOW OF
CONTROL
275
Cno

sbove code, after getting input in ch, compares its value; if value of ch falls between characters
ondition evaluates to true, and thus it will execute the state- ments in the if-body;
ie, the con
to 9
that is, it will print a message saying 'You entered a digit.
consider
Co
another example that uses two if statements one after the other
Now

ch=input ('Enter a single character:')


lf this condition is false then the control will directly reach to
i f ch == following if statement, ignoring the body-of this-if statement
print ("You entered a space")

ifch='0'and ch <='9':
print ("You entered a digit. ")

The above code example reads a single character in variable ch. If the character input is a space,
it flashes a message specitying it. It the character input is a digit, it flashes a message specifying it.

The following example also makes use of an if statement


A=int ( input ("Enter first integer:") )
B int ( input ("Enter second integer:")))
if A> 10 and B< 15:
C (A B) * (A + B)

print ("The result is", C)


print ("Program over") This statement is not part of if statenment as it not indented
at the same level as that of body of if statements.

The above program has an ifstatementwith two statements in its body; last print statement is not
part ofifstatement. Have a look at some more examples of conditional expressions in if statements:

a)if grade == 'A # comparison with a literal


print ("You did wel1")

(6) if a >b: # Comparing two variables


print ("A has more than B has")

(e) ifx # testing truth value of a variable


print ("x has truth value as true")
print ("Hence you can see this message.")

ELave already learnt about truth values and truth value testing in Chapter 8 umder section 84.3A.
acvise you to have a look at section 8.4.3A once again as it will prove very helptul in
understanding conditional expressions.
Now considerone more
test condition:
ifnotx # not x will return True when x has a truth value as false
print ("x has truth value as false this time")
The value of not: will be True only when x is false toa and False when x is truetoa
The above discuss
1ssed plain if statement will do nothing if the condition evaluates to false and
noves to the
next statement tha follows if-statement.
COMPUTER SCIENCE WITH
276
else Statement
9.4.2 The if condition and if
the condition evaluates
-

tests a
evaluates to false, it cam
true, it carie
This form of ifstatement in case
condition arries out statemer
if and
statements
indented below
form) of a
the if-else statement is as shown beloy
The syntax (general
indented below else.
The block
i f<conditional expression>: below if
executed if the
statement
evaluates to true Condita
Istatements] colons after both if and
else
block below elseand
else executed if the
statement evaluates to false. COndition
[statements]

consider the following code fragment:


For instance,
i fa =0:
zero or a positive number")
print (a, "is
else
number")
print (a, "is a negative
For any value more than zero (say 7) of variable a, the above code will print a messaoelike:

7 is zero or a positive number

And for a value less than zero (say-5)


of variable a, the above code will print a messagelike:
-5 is a negative number

Unlike previously discussed plain-if statement, which does nothing when the conditionresuls
action in both cases whether condition is truea
into false, the if-else statement performs
some

false. Consider one more example:


if sales >= 10000:
NOTE
An if-else in comparison to tw
discount = sales * 0.10
successive if statements has les
else wih
number of condition-checks ie,
discount = sales * 0.05 will be teste
if-else, the condition
once in contrast to two comparson
The above statement calculates discount as 10% of sales if the same code is
implemented win
amount if it is 10000 or more otherwise it calculates two successive ifs.

discount as 5% of sales amount.


Following figure (Fig. 9.5) illustrates if and if-else constructs of Python.

Test False Test False


Expression Expression B o d y of else
?

True
True
Body of if Body of if

(a) (6)
Figure 9.5 () The if statement's operation (6) The if-else statement's operation.
: FLOW ODF
OF CONTROL 277
opter 9

now apply this knowledge of if and: e.g Input of numbers 2, 3, 4 will give two sums as

us
Let
in form
of some prograns. 9 and 9
two sums as
ifelse
that
9.1 Program tha takes a number and checks Input of numbers 3,2, 3, will give
number is odd or even.
8 and 2 ( both 3's ignored for second sum)
whether the given as
Input ofnumbers 4, 4, 4 will give two sums
12 and 0 ( all 4's ignored for second sum)
"Enter an integer:" ))
rogram

num = int ( input(


if num
%2 == 0 Alternative 1
"is EVEN number.") sum1 sum2 = 0
print (num, num1 =int(input("Enter number 1 "))
else:
"is ODD number.") num2 int(input('"Enter number 2: "))
print (num, num3 int(input("Enter number 3: "))
This Program
run of abovee in action
The sample sum1 = num1 + num2 + num3
shown below.
code is as if num1 != num2 and num1!= num3
8
Enteran integer: sum2 + num1
number.
8 is EVEN ifnum2!= num1 and num2!= num3:
Scan
sum2 +num2
QR Code
num2
ifnum3!= num1 and num3!=
9.2 Program accept three integers and print
to
sum2 += num3
the largest of the three. Make use of only if:
statement. print("Numbers are", num1, num2, num3)
Irogram
print("Sum of three given numbers is", sum1)
X=y = Z = 0 print("Sum of non-duplicate numbers is", sum2)
X=float (input( "Enter first number :") )
Alternative 2
y float (input( "Enter second number:")) sum1 sum2 = 0
Z= float (input ( "Enter third number :"))
num1 int(input("Enter number 1"))
max X num2 int(input("Enter number 2: "))

ify>maX num3 int (input("Enter number 3: "))


max = y
sum1 num1 + num2 + num3
ifz max
i f num1 == num2
max z
print ("Largest number is", max) if num3!= num1 :

sum2 + num3

Enterfirst number: 7.235 else


Enter second number : 6.99 i f num1 == num3:

Enter third number : 7.533 sum2 + num2


Largest number is 7.533
else
i f num2 == num3

P
9.3 that inputs three numbers
Program and sum2 += num1
calculates two sums as per this
else
rogram Sum2 += num1 num2 + num3
Sum1 as the sum of all input numbers
print("Numbers are", num1, num2, num3)
Sum2 as the sum of non-duplicate
print("Sum of three given numbers is", sum1)
humbers; if there are duplicate numbers in numbers is", sum2)
the input, ignores them
print("Sum of non-duplicate
COMPUTER SCIENCE WITH
278
PYTHON.
9.5 Program to find
Sample
below
run of above program is as shown
D (the divisor) out
the
of multiples of
given five
a
Tunbe
numbers.
Irogram
Enter number 1 : 2
orint ("Enter five numbers below"
Enter number 2 3
Enter number 3 : 4
num1 float (input ("First number
Numbers are 2 3 4 num2 float(input("Second number:"))
Sum of three given numbers is 9 num3 float (input("Third number . "))
Sum of non-duplicate numbers is 9 num4 float (input("Fourth number"
num5 float (input (Fifth number"
Enter number 1 3 divisor =
float(input("Enter divisor nunh
count 0
:"
Enter number 2 : 2
Enternumber 3: 3 print("Multiples of", divisor, are:")
remainder = num1 % divisor
Numbers are 3 2 3
Sum of three given numbers is 8 i f remainder ==

Sum of non-dupli cate numbers is 2 print(num1, sep =" ")

==<<s======<=:=S===== count +1
Enter number 1 :4 remainder = num2 % divisor

i f remainder == 0:
Enter number 2 4
Enter number 3 : 4 print(num2, sep =" ")

Numbers are 4 4 4 count + 1


Sum of three given numbers is 12 remainder = num3 % divisor

Sum of non-duplicate numbers is 0 if remainder ==0


print(num3, sep =" ")

COunt += 1
remainder = num4 % divisor
9.4 Program to test the divisibility of a number:
i f remainder == 0
with another number (i.e., if a number is
print (num4, sep =" ")
divisible by another number).
rogram count+=1
remainder = num5 % divisor
number1 = int (input("Enter first number: "))
if remainder == 0:
number2 int (input("Enter second number:")) print(num5, sep =" ")
remainder = number1% number2
count + 1
i f remainder == 0:
print()
print (number1, "is divisible by", number2) print(count, "multiples of", divisor, "found
else:
print(number1, "is not divisible by", number2) Sample run of above program is as Si
1 below:

Enter first number : 119 Enter five numbers below


Enter second number : 3
First number : 185
119.0 is not divisible by 3.0
Second number : 3450
======SS:==========
Third number : 1235
Enter first number : 119
Fourth number: 1100
Enter second number : 17
Fifth number: 905
119.0 is divisible by 17.00
Enter divisor number: 15

Enter first number: 1234.30 Multiples of 15.0 are:


Entersecond number 5.5 3450.0
1234.3 is not divisible by 5.5 1 multiples of 15.0 found
CONTROL
279
Chopter 9 :
FLOW OF
F l o

9:

displajy a menu for calculating area of a circle or perimeter of a circle.


Program to
9.
radius ("Enter radius
=float ( input of the circle:" ))
Calculate Area")
Irogram print ("1.
print ("2. Calculate Perimeter")
int (input( "Enter your choice (1 or 2) :" ))
choice =

1:
i fchoice
==

*
3.14159 * radius radius
area
of circle with radius", radius, 'is', area)
print ("Area
else:
* radius *
= 2 3.14159
perm
("Perimeter of circle with radius", radius, 'is', perm)
print

radius of the circle


: 2.5
Enter
1. Calculate Area

2. Calculate Perimeter

choice (l or 2) : 1
Enter your radius 2.5 is 19.6349375
Area of circle wi th
==S5SSSS-S5=SSSSSS=E RESTART===

the circle : 2.5


Enter radius of
1. calculate Area
2. Calculate Perimeter

Enter your choice (1 or 2) : 2


radius 2.5 is 15.70795
Perimeter of circle with
statement
be any relational expression logical or a

Notice, the test condition if of statement can


statement is a compound statement,
hence
that results into either true orfalse). The if it.
ie, a statement must be indented below
end in a colon and statements part of it
its both if and else lines must

if r u n s a r e more than 100


9.4.3 The if - elif Statement
another then it is a century
check
Sometimes, you need to than 50
runs a r e more
condition in case the test-condition of if else if

That is, you want to then it is a fifty


evaluates to false.
reaches
check a condition when control else
else part, i.e., condition test in
the form of batsman has neither
scored a century nor fifty
this
else if. To understand this, consider
adjacent example. used if inside another
if/else.
earlier, where w e have
ETer to program 9.3 given if-elif and
inside a n else), Python provides
above i.e., in else if form (or if
serve conditions as
0 The general form of these
s t a t e m e n t s is

E n e l s e statements.
if<conditionalexpression»
and statement
if <conditional expression>
statementt [statements]
elif <conditional expression>
[statements]
statement
elif<conditional expression
statement
[statements]
else
[statements] statement
NOTE
, elif and else all are block or compound statements.
[statements]
280
cOMPUTER SCIENCE WITH

be coded in Python as:


PY
PITHON
Now the above mentioned example can

if runs >= 100 :


century") Python will test this
previous COndition ( condition
scored a
To see print ("Batsman runs > t
if-elif Statement
100) is
in action elif runs >=50: This block will be falk
scored a fifty") executed
if's condition ( 1.e., runs when both the
print ("Batsman
condition ( 1.e., runs> >=100
else:
=50) are f unml
scored a century fifty
atse.
print ("Batsman has neither
nor

Scan
Let us have a look at some more code examples:
OR Code

ifnum < 0:
print (num, "is a negative number. ")
e l i f num == 0 :

print (num, "is equal to zero.")


else
print (num, "is a positive number.")

Can you make out what the above code is doing ? Hey, don't get angry. I was just kidd.
I know you know that it is testing a number whether it is negative ( < 0 ), or zero(s0 dding
positive (>0). Consider another code example :
0)or
i fsales >= 30000:
discount = sales * 0.18

elifsales = 20000
discount = Sales * 0. 15

elifsales >= 10000 There can be as many elif blocks as you need.
Here, the code is having two elif blocks
discount =sales *0.10
else
This block will be executed when none of
discount =sales *0.05 above conditions are true.

Consider following program that uses an if-elif statement.


9.7 Program that reads two numbers and an arithmetic operator and displays the computed result.

num1 float ( input( "Enter first number:") )


Trogram num2 float ( input( "Enter second number: ") )
op =input ( "Enter operator [+- * /%]:")
result =0
Enter first number : 5
if op == '+:
Enter second number: 2
result = num1 + num2 :*
Enter operator [+ -

*/%
elifop ==' 5.0 2.0 10.0
result = num1 - num2
=== RESTART ===*

elif op == '*:
Enter first number :5
result = num1 * num2
Enter second number: 2
elif op =='/': Enter operator [ + - * / %]:/
result =num1/ num2
5.0/2.0 2.5
elif op =='%': ======= RESTART +=
result = num1% num2
Enter first number : 5
else Enter second number: 2
print ("Invalid operator!!") Enter o p e r a t o r [ +
-

* /%]:*
print (num1, op, num2, '=, result) 5.0% 2.0 1.0
FLOW
OF
CONTROI
281
Chapter
9:
Now try writing code of program19.3 using if-elif-else statements.

The
nested if Statement
44
S o m e
imes above discussed forms of if are not enough. You may need to test additional
t i m e s

conditie such situations, Python also supports nested-if form of if.


Fors

ted if is an if that has another if in its ifs body or in elifs body or in its else's body.
Thenestedifcan have
one of the followi
forms:
if's body) Form 2 ( if inside elif's body )
Form 1 (ifinside
if <conditional expression» if <conditional expression>
i f <conditional expression> statement
statement (s) statements]
else elif<conditional expression>
statement(s) if <conditional expression>
elif <conditional expression> statement(s)
statement else:

[statements] statement(s)
else else
statement statement
[statements] [statements]

Form 3( if inside else's body) Form 4 (if inside if's as well as else's
or elif's body, i.e., multiple its inside)

if <conditional expression> if <conditional expression>


statement if <conditional expression> :

[statements] statement(s)
else
elif<conditional expression>
statement statement(s)
elif <conditional expression>
statements]
else if <conditional expression>:
statement (s)
if<conditional expression>
else:
statement(s) statement(s)
else
else
statement(s)
if <conditional expression>
statement(s)
else
statement(s)

a nested if statement, either there can be if statement{s)


in its
body-0f-if or in its body-of-elif or
all of these. Recall that you used nested-if
Its body-of-else or in any two of these or in
snowingly in program 9.3. Isn't that superb ?;)
Followin example programs illustrate the of nested ifs. use
282 COMPUTER SCIENCE TH PYTHON -
and prints them in ascending order
Program that reads three
numbers (integers)
9.8
Irogram X= int(input( "Enter first number: "))

y int(input( "Enter second number: "))


Z= int(input( "Enter third number: " ))
min = mid = max = None

ifx < y and x < z:

i fy< z
min, mid, max =
X, y, z Two sample runs of the program
else are as given below
min, mid, max = X, Z, y
Enter first number : 5
elify < x and y < z Enter second number: 9
Enter third number: 2
ifx<z:
min, mid, max =
y, X, Z Numbers in ascending order : 2 59
else RESTART==
min, mid, max = y, Z, X
Enter first number: 9
else Enter second number: 90
ifx<y : Enterthird number: 19
min, mid, max = z, X, y Numbers in ascending order 1 19 90
else:
min, mid, max = z, y, x

print ("Numbers in ascending order: ", min, mid, max)

Let us now have a look at some programs that use different forms of if statement.

9.9 Program to print whether a given character is an uppercase or a lowercase character or a digit or

any other character.


lrogram

ch input( "Enter a single character:")


if ch = 'A and ch <="Z': of the program is showT
Sample run as

print ("You entered an Upper case character. ") below


elif ch = 'a' and ch <="Z: Enter a character : 5
print ("You entereda lower case character.") You entered a digit.
=======<s= RESTART ===
elif ch = '0' and ch <='9' Enter a character : a
print ("You entered a digit.") YOu entered a lower case charactel
==== RESTART ===

else
Enter a character: H
print ("You entereda special character. ") YOu entered an Upper case characte
====<== RESTART ====
Enter a character : $
YOu entered a special character
FLOW OF
CONTROL 283
Chapter9:

Program to calculate and print roots of a quadratic equation: ax +bx +C =0 (a 0 ) .


9.10

rogram

import math

orint ("For quadratic equation, ax**2 + bx + c = 0, enter coefficients below")

a int( input (" Enter a:"))


b int( input ( " Enter b:"))
"

c int( input ( Enter c " ))


if a == NOTE
print ("Value of", a, 'should not be zero') You can use sqrt() function of math package
to calculate squareroot of a number. Use it as:
print ("\n Aborting !!!!")
else math.sqrt (<number or expression>)
delta b *b -4 * a*c
To use this function, add first line as
if delta>0 import math to your program
root1 ( - b + math. sqrt(delta)) / (2 * a)

root2 (-b - math.sqrt ( d e l t a ) ) / (2 * a)

print ("Roots are REAL and UNEQUAL")


print ("Root1 =", root1, ", Root2 =", root2)

elifdelta ==0:
root1 = - b / (2 * a ) ;

print ("Roots are REAL and EQUAL")


NOTE
print ("Root1 =", root1, ", Root2 =", root1))
An if statement is also known as
else a conditional.
print ("Roots are COMPLEX and IMAGINARY")

FOr quadratic equation, ax**2 + bx + c = 0, enter coefficients beloww


Enter a : 3
Enter b:5
Enter c : 2
Roots are REAL and UNEQUAL
-1.0
Rootl =-0.666666666667 ===
Root2
RESTART
=

SSS:SSSSSSSSS:

For quadratic equation, ax**2 + bx + c = 0, enter coefficients below

Enter a : 2
Enter b : 3
Enter c : 4
KOots are cOMPLEX and IMAGINARY
==== RESTART ==*

bx C =0, enter Coefticients below


O quadratic equation, ax**2 +

Enter a : 2
Enter b : 4
Enter c :2
Roots are REAL and EQUALL
ROotl= -1, Root2
=1
284 cOMPUTER NITH PYTHON -
SCIENCE WITH
PYT

Storing Conditions
Sometimes the conditions being used in code are complex and repetitive. In such ea.

your program more


readable, you can use named conditions i.e., you can store c es, to make
name and then use that
named conditional in the if statements.

Forexample, to create conditions


similar to the ones given below:
I f a deposit is less than 2000 and for 2 or more years, the interest rate is 55 .percent.
Ifa deposit is {2000 ormore but less than R6000 for 2 or more years, the i
7 percent. rate is
I f a deposit is more than R6000 and is tor 1 year or more, the interest is 8 cent.

O n all deposits for 5 years or more, interest is 10 percent compounded annualhr

C h e c k P o i n t
The traditional way of writing code will be
9.2
i fdeposit < 2000 and time = 2
1. What is a selection statement? Which rate = . 0 5

selection statements does Python provide ?


2. How does a conditional expression affect
the result of if statement? But if you name the conditions
separately and use them
3. Correct the following code fragment: later in your code, it adds to
readability and under
if (x = 1) standability of your code, eg,
k 100
else
eligible_for_5_percent deposit < 2000 and time =2
eligiblefor_7_percent = 2000<= deposit <6000 and time >= 2
k = 10

4. What will be the output of following code


eligible_for_8 percent deposit> 6000 and time =1
eligible_for_10_percent = time >= 5
fragment if the input given is (i) 7 (i) 5?
a input(Enter a number") Now you can use these named conditionals in the code as
if (a == 5):
follows
print ("Five")
else ifeligible_for_5_percent:
print ('Not Five") rate 0.05
5. What will be the output of the following
code fragment if the input given is (i) 2000
elif eligible_for_7_percent:
i) 1900 (iü) 1971 ? rate 0.075
.
year int(input ( "Enter 4-digit year"))
if (year % 100 == ) :
if (year % 400 == 0):
TIP
You can use named conditions in f
print ("LEAP century year") statements to enhance readabilty
else
and reusability of conditions.
print ("Not century year")
6. What will be the output of the following
code fragment if the input given is (i) 2000
DECISION
() 1900 (iü) 1991 ? CONSTRUCT if 9.1
year = int(input( "Enter 4-digit year"))
iP Progress In Pyhon
if (year % 100 == 0)
This Progress in Python' session is aimed at laying
if (year % 400 == ®)
strong foundation of decision constructs.
print (LEAP century year")
else:
print ("Not century year") >>>ek<
:FLOWOF CONTR
285
C h o p t e r 9

OF TASKS -

A NECESSITY
a5 REPETITION
9.5 same sett or tasks
earlier that there are many situations where you need to repeat
We mentioned mentioned earlier.
again and again eg,
the tasks of
making chapatis/dosas/appam at home, as
to write pseudocode for this task how would you do that.
Now if you have
Let us first write
the task of making dosas/appam from a prepared batter.
1. Heat flat pan/tawa
2. Spread evenly the dosa/appam batter on the heated flat pan.

3. Flip it carefully after some seconds.


4. it again atter some seconds.
Flip
5. Take it off from pan.
6. To make next dosa/appam go to step 2 again.
want.
as you
pseudocode for above task of making dosas/appam many
as
Let us try to write

#Prerequisites Prepared batter


Heat flat-pan/tawa
Spread batter on flat pan
20 seconds
Flip the dosa/appam after
20 seconds
Flip the dosa/appam after
Take it off from pan
if you want more dosas then

else
stop
of ????, so that it starts repeating the process again
Now what should you write at the place one tell from where
number associated with steps, how can
from second step? Since there is no
to repeat ?
where you want to repeat
There is label that marks the statement from
If there is a
a way out: then that statement onwards,
may send
the control to that label and
the task, then we
statements get repeated. That is,

Pseudocode Reference #Prerequisites prepared batter


Heat flat-pan

Spread: Spread batter on flat pan


20 seconds
F l i p the dosa/appam after
Label given to this after 20 seconds
statements
Flip the dosa/appam
Take i t off from pan

more dosas then


If you want
from here the control Go toSpread
will go to spread
batter.. step and all
steps following it will Else
be repeated.
Stop Dotted arrows show how the control flows
from one statement to another/
END
286 COMPUTER SCIENCE WITH
PYTHON-
Now the above pseudocode is fit for making as many dosas/appam as you want. But
you already know that you need only 6 dosas/appam ? In that case above pseudocoda t f
serve the purpose.
ode will not
need to maintain
Let us try to write pseudocode for this situation. For this, we need
maintain a c a
dosa/appam made.
T
count of

Pseudocode Reference 2

#Prerequisite : prepared batter


A. Heat flat pan
B. Initialize count to0
C. Spread: Spread batter on flat pan
D. Flipthe dosa/appam after 20 seconds
E. Flipthe dosa/appam after 20 seconds
F. Take it off from pan
G. Add 1 to count
H. If count==6 theen

Stop
Else
Go to spread Dotted arrows show how the control flows
jrom one statement to another|
3. End

If we number the
pseudocode statements as A.B.C.... as shown above for
notice carefully, the statements our reference, if you
are executed as:

A B CDEFGHI CDEFGHI CDEFGHI


Statements
repeated

CDEFGHI CDEFGHI
L CDEFGHI 3.
You can see that statements C to I
are
repeated 6 times or we can say that loop
repeated b tined
This way we can
develop logic for
carrying repetitive tasks, either based on
out
(pseudocode reference 1) or given number
a
of times condiuo a

To carry out (pseudocode reference 2).


repetitive tasks, Python does not have any es
following iterative/looping statements: go to statement rather it
prov
Conditional loop while (condition based loop)
Counting loop for (loop for a given
number of times).
Let us learn to write code for
repetitive tasks, in Python.
9:
Choprer
FLOW OF CONTROL 287
FUNCTION
96 THE range( )
.0
Before we start with loops, especially for loop of Python, let us discuss the ranget) function of
Python, which is used with the Python for loop. The range () function of Python generates a list
which is a special sequence type. A sequence in Python is a succession of values bound together
hva single name. Some Python sequence types are: strings, lists, tuples etc. (see Fig. 9.6). There
are some advance sequence types also but those are beyond the scope of our discussion.

7) tuplel
Listi
Contains
elements

A List A tuple
To see
range) Function
String1 "good"
A sequence is a
succession of values
g ' o ' "o' 'd* bound together by
a single name.
A string
Scan
Figure 9.6 Some common sequence types QR Code

of range( is in the form given below:


Letus see how range( ) function works. The
common use

<lower limit>, <upper limit») # both limits should be integers


range(

The function in the form range(1, u) will produce a list having


values starting from l,I+1, 1+2
the lower limit is included in the list but
.. (u -1) (l and u being integers). Please note that
upper limit is not included
in the list, e.8,
values will be +1
the default step-value in
range(0,5) *
will produce list as [ 0, 1, 2, 3, 4 1
that begins with lower limit 0 and goes
As these are the numbers in arithmetic progression (a.p.)
up till upper limit minus 1 i.e., 5-1 =4.
+1
default step-value
=

range(5,0) * --
with 5 and ending at 0 (difference
falls in the a.p. beginning
will return empty list [ ] as no number
d or
step-value +1}).
=

=
+1
default step-value
range(12, 18)

Will give a list as [12, 13, 14, 15, 16, 17].


numbers increasing by value
1. What if you want
All the above examples of range() produce want to produce a list like [2, 4,
other thanl, e.g, you
produce list a with numbers having gap
, 8]using range() function ? function:
Such lists, you c a n use following form of rangel)
#all values should be integers
<step value>)
<upper limit>,
dnge( <lower limit>,
COMPUTER SCIENCE WITH
PYI ON
288

That is, function

#l, u and s are integers


range(1, u, s)
1.
will produce a list having values as 1, I+ s, l+2s, ... <=l-
**step-value = +2
range(0, 10, 2)
will produce list as [0, 2, 4, 6, 8] NOTE
Step-value = - 1 | A sequence in
Python
--

range (5, 0, -1) " -***

succession of values bound


is a

will produce list as [5, 4, 3, 2, 1]. together by a single name e.g.


list, tuple, string. The
Another form of range() is: range(
returns a sequence of list
type
range(<number>)

0 (zero) to <number> 1, e.8, consider folloWing range() function


that creates a list from
-

range(5)
The above function will produce list as [0, 1, 2, 3, 4]. Consider some more examples of nget)

function:
Values generated
Statement
9
range(10) 0, 1, 2, 3, 4, 5, 6, 7, 8,
5, 6, 7, 8, 9
range(5, 10)
3, 4, 5, 6
range(3, 7)
range(5, 15, 3) 5, 8, 11, 14

range(9, 3, -1) 9, 8, 7, 6, 5, 4

range(10, 1,-2) 10, 8, 6, 4, 2

Operators in and not in


Let us also take about in operator, which is used with ranget ) in for loops.
To check whether a value is contained inside a list you can use in operator, e8,
This expression will test if value 3
3 in [1,2,3,4]4- is contained in the given sequence
NOTB
will return True as value 3 is contained in sequence [1, 2, 3, 41. tests if a given
The in operator
contained in a
sequence
5 in [1,2, 3,4] value is
False
returns True or
or not and
will return False as value 5 is not contained in sequence [1, 2, accordingly
3, 4]. But

5 not in [1,2,3,4]
he'
+ ***
will return True as this fact is true that as value 5 is not contained in sequence |1,
operator not in does opposite of in operator. sick a

You can see that in and not in are the operators that check for membership ota Vwo Operators work
with

sequence. Thus, in and not in are also called membership operators. These operato
all sequence types i.e., strings, tuples and lists etc.
o:
FLOW OF
CONTROL
289
Cnapte

Forexample, consider:following code


a' i n " t r a d e "

will return True.as 'a is contained in


sequence (string type) "trade"
"ash" in "trash"

urill also return


True tor the same reason. NOTE
Now consider the following code that uses the in operator: Operators in and not in are also
called membership operators.
"Enter a line :")
1ine input(
string input( "Enter a string:" )
if the given string is a part of line

ifstring in line:.
print (string, "is part of", 1ine.)

else

print (string, "is not contained in", line.)

You can easily make out what the above code is doing - it is checking whether a string is
contained in a line or not.

Now that you are familiar with range() function and in operator, we can start with Looping
(Iteration) statements.

9.7 ITERATION/LOOPING STATEMENTS


The iteration statements or repetition statements allow a set of instructions to be performed
repeatedly until a certain condition is fulfilled. The iteration statements are also called loops or
looping statements. Python provides two kinds of loops : for loop and while loop to represent fwo
categories of loops, which are :
the loops that repeat a certain number of times; Python's for loop is a
counting loops
counting loop.
conditional loops the loops that repeat until a certain thing happens ie., they keep
repeating as long as some condition is true ; Python's while loop is
conditional loop.
To see
9.7.1 The for Loop for Loop
in action
The for loop of Python is designed to process the items of any sequence, such as
aSt or a string, one by one. The general form of for loop is as given below
-*********-
This determines how many time the loop
A
for <variable> in will get repeated.
<sequence> Scan
*****uw.*
. Colon is must here
QR Code
statements_to_repeat. ***here the statements to be repeated

Forexample, consider the following loop: will be placed (body-of-the-loop)

ne loop variable a.
bghed each value ofVariable
list one
a will be for a in [1, 4, 7]: This is the body of the for loop. All statements
for the first time a by one, in the body of the loop will be executed for each
then 7
will be 1, then print (a)-
value of loop variablea, i.e., firstly for a =1;
print(a *a) then for a = 4 and then for a=7
COMPUTER SCIENCE WITHM
290 PIHG
as
A for loop in Python processed
is
the sequence.
the first value in
The loop-variable is assigned
a l l the statements in the body offor
loop are executed value ot
with assigned vals.
lo0p variak
(step 2) the
once step 2 is over,the loop-variable
is assigned
and the loop-body is
NOTE
next value in the sequence Each time, when the
the new value of
executed (i.e., step 2 repeated) with executed, is called anloopth
loop-variable.
are
teration
in thè sequences
This continues until all values
processed.
for a in [1, 4, 7]:
will be
That is, the given for loop
print (a)
processed as follows p r i n t (a * a) -body of the
loop
will
)firstly, the loop-variable a

be assigned first value of list


) a =
i.e., 1 and the statements in the
a assigned first value and with
body of the loop will be
this value, all statements in
executed with this value of a.
Hence value 1 will be printed loop body are executed
prints
with statement print(a)' and print (1) --***---**********
value 1 will again be printed print (1*1). - -******m********** 1
with print(a*a). (see execution prints

shown on right)
a = 4
'

(i)
(i) Next, a will be assigned next a assigned next value and
value in the list i.e., 4 and loop-
loop body executed with a as 4: prinis
body executed. Thus 4 (as result print (4)
---****-*-----*.- 4

of print(a)) and 16 (as result of 6


print (4*4) *********************

prinis
printfa a)) are printed.

(ii) Next, a will be assigned next (ii) a 7


value in the list ie, 7 and loop- a assigned next value and
body executed. Thus 7 (as result loop body executed with a as
7
prinis
of printa)) and 49 (as result of print (7)
***********

printla*a).are printed. p r i n t ( 7 * 7 ) *****--**---w*--*******

Pris

(iv) All the values in the list are


executed, hence loop ends. No more values

Therefore, the output produced by above for loop will be:


1

4
16.
7
49
CONTROL
o p r

9:
e r 9 .
FLOW OF 291

Consider another for loop NOTE


for ch in'cal
) for loop ends when the loop is
print (ch) repeated for the last value of the
sequence.
The above loop will produce output as:
(i) The for loop repeats n
C
number of times, where n is the
length of sequence given in
for-loop's header.

(variable ch given values as'c, 'a', T, 'm' - one at a time from string 'calm'.)

Here is another for loop that prints the cube of each value in the list:

for v in (1, 2, 3]:


print (v *v*v)
The above loop will produce output as:

8
81
The for loop works with other sequence types such as tuples also, but we'll stick here mostly to
lists to process a sequence of numbers through for loops.
As long as the list contains small number of elements, you.can write the list in the for loop
directly as we have done in all above examples. But what if we have to iterate through a very
largelist such as containing natural numbers between 1-100 ?. Writing such a big list is neither
easy nor good on readability. Then ? Then what? Arey, our very own range() function is
there to rescue. Why worry? ;) For big number based lists, you can specify range() function to
represént a list as in

for val in range(3, 18):


print (val)
In the above loop, range(3, 18) will first generate a list [3;4, 5, .., 16, 17] with which for loop will
work. Isn't that easy and simple ?©
You need not define loop variable (val above) before-hand in a for loop. Now consider following.
code example that uses range( ) function in afor loop to print the table of a number.

9.11 Program tò print table of a number, say 5


I rogram
num 5
5x 1 5
for a in range(1, 11): 5 x 2 = 10
print (num, 'x, a,'=', num * a) Sx 3 15
5 x 4 20
Lhe above code will print the output as shown here : 5 x 5 25,
5.x 6 = 30
NOTE 5 x 7 35
TOu
need
5x8 =40
not
variable of a for pre-define loop 5x 9 45
toop. 5x 10 = 50
COMPUTER SCIENCE WITH
NTH PITHON-
292 P

natural numbers between 1


to 7. Print the sum nro.
9.12 Program to
adding each
print sum of
natural number, print sum so far. progressively, i.e.,
Sum of natural
Irogram
sum of natural
numbers
sum numbers is
Sum of natural
for n in range (1, 8):
sum of natural numbers
is3
Sum of natural numbers<=4-
sum+= n
4 is
print ("Sum of natural
numbers (=", n, "is", sum) numbers 5
Sum of natural
Sum of natural
numbers <= 6 i
The above code will print the output as shown here: numbers <=7
isi 28
print sum of natural numbers between 1 to 7.
9.13 Program to

sum 0
Sum of natural
Irogram for n in range (1, 8): numbers=7 is
sum + n
print ("Sum of natural numbers <=", n, 'is', sum)

Carefully look at above program. t again emphasizes that NOTE


body of the loop is defined through indentation and one more The
fact and important one too the value ofloop variable after the loop variable contains the
for loop is over, is the highest value of the list. Notice, the above highest value of the list after the
for loop is over. Program 9.13
loop printed value of n after for loop as 7, which is the highlights this fact.
maximum value of the list generated by rangel1, 8).

9.7.2 The while Loop


A while loop is a conditional loop that will repeat the instructions within itself as long as a
conditional remains true (Boolean True or truth value true toa). The general form of Python while
loop is:

while <logicalexpression>:
loop-body
where the loop-body may contain a single statement or multiple statements or an emnpty statement
i.e, pass statement). The loop iterates while the logical expression evaluates to true. When tne
expression becomes false, the program control passes to the line after the loop-body.
To understand the
working of while loop, consider the following code:
a = 5
This condition is tested, if it is true, the loop-body is
while a> 0: executed. Ajter the loop-body's execution, the condition
is tested again, loop-body is executed long as
print ("hello", a) condition is true.
as

a a-3 The loop ends when the condition evaluates to false


print ("Loop Over!!")
The above code will
print:
These hvo lines are the result
hello 5 execution (which executed
hwice).
of while loops' body
hello 2
Loop over!! This line is because of
print statement
after the while loop.
LOW OF CONTROL 293
Chopter
while a >o:
see
ho how a hile loopis
print ("hello", a)
us
Let
processed: -** body of the
a =a 3 loop

n 1 T h e l o g i litional expression
c a l l c o n d i t i

a > 0 above) [a has value 5 before entering into while loop]


SePin the while loop (eg,
i s e v a l u a t e d .

() while's condition tested with a's current value as 5


result of step 1 is 5 True
Case I if the
Step2 true (True or true toa) hence loop's body will get executed
then all statements in
print ("hello", 5) - ****helloo5
the loop's body are a = 5-3 =2. (a becomes 2 now)
prints
executed, (see section (i)
& (i) on the right).
result of step 1 is (i) while's condition tested with a's current values 2
Case II if the
false (False or false toni) 2 0 =True
then control moves to loop body will get executed
the next statement after
print ("hello", 2) hello 2
the body-of the loop i.e., prints
loop ends. (see section a
=2-3 =-1 (a becomes -1 now)
(ii1) on the right).
(ii) while 's condition tested with a's current value -1
Step 3 Body-of-the loop gets executed.
-1> = False
This step comes only if Step 2,
Case I executed, i.e., the result of loop body will not get executed
logical expression was true. This control passes to next statement
step will execute two statements after while loop
of loop body.

Ater executing the statements of


loop-body again, Step 1, Step 2 and Step 3 are repeated as long
as the condition remains true.
The loop will end only when the logical expression evaluates to NOTE
jalse. (i.e., Step 2, Case II is
executed.) Consider another example:
n =1 The variable used in the
condition of while loop must
while n < 5:
have some value before
print ("quare of", n,'is', n* n) entering into while loop.
n+ 1

print ("Thank You.") This statement is not part of the loop-body


he above code will print output as
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9 These lines of output are because of the
loop-body execution (loop executed 4 times)
Square of 4 is 16
Thank You.
Thus you see
(for val that as longg as the condition n< 5 is true above, the while loop's body is executed
lOop
P is
IS ev", n=2 n=3, n=4). After exiting from the loop the statement following the while
executed that prints Thank You.
COMPUTER SCIENCE WITH Dy
294 YTHON
Control Elements)
while Loop (Loop
Anatomy of a its executionn. A

Every while loop has its elements


that control and govern
These e l e m e n t s are as given below
loop has four while
purposes.
elements that have different
wlhile loop, the test-expression
In aa uwhile test-expr
Expression(s) (Starting). Before nbefore is
1.Initialization
a while loop,
its loop variable must be:
entering into a loop. evaluated
entering inThe
initialized. initialization.of the 10Op vari 3. The Body-of-the-Loop (Doing) T
under initialization The statements
control variable) takes place
that are executed repeatedly (as lono
ong i
expression(s).
The initialization expression(s)
The
test-expression is trHe) form the body of the the
give(s) the loop variable(s) their first value(s). In while loop, betore looy.
initialization expression(s). for a while loop are
a
every
iteration
test-expression is evaluated and if it is trie the
the while loop before it
starts. ,the
outside body-of-the-loop is executed; if the
2.Test Expression (Repeating Stopping).
or The evaluates to false, the loop is terminated. expression
an expression
whose truth;
test expression is will be:
4.Update Expression(s)
(Changing). The updat
value decides whether the loop-body exprèssions change the value of loop variable. The
evaluates
executed or not. If the test expression update expression is given as a statement inside
to triue, the loop-body gets executed, otherwise the body of while loop.
the loop is terminated..

Consider the.following code that highlights these elements of a while loop


Test expression: based on this condition,
Initialization expression 10
loopiterates i.e., repeaus.-
initializes loop variable. while n>6: .

Body of the loop


print (n) Update expression : changing value of
(contains indented staiements
beneath while) n- 3 loop variable

Other important things that you need to know related to while loop are:
I n a while loop, a loop control variable should The loop variable must be updated inside ne
be initialized befóre the loop begins as in way that after
some
time
an body-of the-while a
the
uninitialized variable cannot be used in an the test-condition becomes false otherwise
or intinie
expression. Consider following code: loop will become an endless loop

loop. Consider following code


while p != 3: This will result in error if a = 5
variable p has not.been
ENDLESSLOOP! Becausete
5 ahuu
created beforehand. while a >0: 0op-variable
a

value is
remains

not updated
m
a s its
print (a) the loop-body.
hence-tme u
print ("Thank You") dition

ne above loop is an endless loop as the value of loop-variable a is not being upa
loop body, hence it always remains 5 and the loop-condition a > 0 always Te
To see
The corrected form of
while Loop above loop will be
in action a 5

while a> 0:. Loop variable a being updated


print (a) inside the loop-body.
a-1
Scan
OR Code
print ("Thank You")
F L O WOF CONTROL
Choper: F l

295
talk about infinite loops 'once again after
We will

statement is discussed.
the break
NOTE
Sincein a while loop, the control in the form of condition-check is
To cancel .the
of tthe
of loop (loop 1s not entered, if the condition is running of an
the entry endless. loop, you can press
at
it is
an example of an
entry-controlled
entry- loop.
-Controlled loop is a loop that controls the entry in the loop by
-An .CTRL+C keys anytime
during its
endless repetition to stop it.
testinga
condition. Python does not offer any exit-controlled loop
condition

srOt are fámiliar with wh1le loop, let us writé


some
Now
programs that make use of
while loop.

a 14 Program to calculate
the factorial of a number.
num int( input ( "Enter a number:" ) )
LJogialm
fact 1
a 1 This program
in action
while a <=num :
fact *= a # fact fact*a
a t 1 #a = a+ 1

print ("The factorial of, num, "is", fact) Scan


QR Code

Sample runs of above program are given below


Enter a number : 3
The factorial of 3 is 6
====S====ZEFEE:5E:5EE=55 RESTART ===

Enter a nutber: 4

Thefactorial of 4 is 24

and odd integers of the first n natural numbers.


l 3 , Program to calculate and print the sums of even
number ?"))
ogram nint(input( "Up to which natural
ctr 1
Sum_even = sum_odd = 0

while ctr <= n:


# number.is even
if ctr% 2 == ®:
sum_even += Ctr

else
ctr
sum,odd += #increment the counter
ctr1
is" sum_even)
PrLnt ("The sum of even integérs
,

is", Sum_odd)
PrLnt ("The sum of odd integers
output produced by above code is
Up to which
The sum of natural numbber? 25

Sum
even integers is 156
of odd is 169
integers
296 cOMPUTER SCIENCE WITH
PYTLue
THON
Statement
9.7.3 Loop else
and while loop) have an else clause, which
loops of Python (i.e., for loop
.
Both s ifferent from
The else of a loop executes only when en the
ends loop
else of if-else statements.
only when the loop ending
is because the while loop's test condition has resusle
ted normal
in
ly (ie.
last value in sequence.) You'l learn m in the false or
for loop has executed for the
the loop, while loop is
next
section that it:the
break statement is reached in
terminated pre-maturely e v e n if the test-condition is
still true NOTE
or all values of sequence have not been
used in for loop.
a
The else clause of a
Python
In order to fully understand the working of loop-else clause, it executes when the loon
loop
Thus terminates normally, not when
will be useful to know the working of break
statements.
the loop is
back terminating because
let us first talk about break statement and then we'll get of a break
statement.
to loop-else clause again with examples.

9.7.4 Jump Statements break and continue NOTE


used within loops to
Python offers two jump statements to be A break statement skips the rest
of the loop and
break and continue
jump out of loop-iterations. These are the statement
jumps over to
statements. Let us see how these statements work. following the
loop
9.7.4A The 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.


The following figure (Fig. 9.7) explains the working of a break statement

while <test-condition>: for <var> in <sequence>:


statement 1 statement 1

if <condition> i f <condition>
Statements 4 is the break break
first statement after statement 2 statement 2
statement 3
t e

the loop statement 3 efminat


statement 4 Loop t e r m i statement 4 Loop
statement 5 statement 5

Figure 9.7 The working of a break statement.

The following code fragment gives you an example of a break statement


a =b c =0
for i in range(1, 21):
a = int (input ( "Enter number 1"))
b int (input ( "Enter number 2:" ))
ifb== 0:
print ("Division by zero error! Aborting! ")
break
else
Ca// b
print ("Quotient = ", c)
print ("Program over !")
CONTROL
ar9:
FLOW OF
C n a p

above fragment intends to divide ten


de
code fra 297
The
iteration.
h iteration If the
each pairs of numbers by
number b is zero, the
d b in inputting two numbers a
loop is immediately
Division by zero error! Aborting
displayed.
are
otherwise the numbers areterminated displaying
their quotients repeatedly input and
Sample run of above code is given below :
NOTE
1: 6
Enternumber A loop can end in two ways: if
2: 2 (i)
Enternumber the while's
condition results in
Quotient = 3 This message is false or for loop
1: 8 break statement. printed just prior to execution
Notice that the next of last value of the
executes with
Enter number because of the statement message is sequence
Enter number
2: 3 outside the loop. That is. (NORMAL TERMINATION). (i) Or
after break, next statement to be if during the loop execution,
Quotient= 2 statement executed is the
outside the loop. break statement is
Enternumber 1: 5 executed. In
this case even
2 0 if the conditionis
Enter number true the for has not
or
executed
pivision by zero error! Aborting! all the values of
Program Over !
sequence, the
loop will still terminate.

Consider another example of break statement in


the form of
following program.
9.16 Program implement 'guess the number'
to
range[10, 50]. The user is given five chances togame. aPython generates a number
randomly in the
guess number in the range 10<=number
rOgran <=50.
f the user's guess matches the number
terminates without generated, Python displays "You win' and the
loop
completing the five iterations.
If, however, cannot guess the number
in five attempts, Python displays 'You lose'.
Togenerate a random number in a
range, use
following function:
random.randint (lower limit, upper limit)
Make sure to add first line as
import random
import random
number
ctr
=

random.randint (10, 50)*- This will generate a number


within the range 10-50.
randomly,

while ctr <5:


uess int(input( "Guess a number in range 10..50 )
ifguess ==
number:
print ("You win!! :)")
break The moment this statement is reached the loop will
terminate without completing all iterations, even if
else
the loop condition ctr < 5 is still true.
ctr+ 1
ifnot ctr < 5: #i.e., whether the loop terminated after 5 iterations
2ntYou lose : ( \n The number was", number)
COMPUTER SCIENCE WITH PYTH
YTHON K
298
is as shown below:
Sample run of above program

10..50 31.
Guess a number in range 23
10..50:
Guess a number in range 10..50 34
Guess a number in range 10..50 40
Guess a number in range
1 0 . . 5 0 : 50
number in range
Guess a
You 1ose :(
The number was 28
RESTART
39
number in range 10..50
:
Guess a
46
number in range 10..50
:
Guess a
statement executed.
You win!! :) At this point the
break

is terminàted becauso
From the above program, you
can make out that if the while loop se of a

of the while loop will still be true


outside the loon even
break statement, the test-condition 0op.
Thus, you can check the test-condition outside the loop to determine what caused the p

termination the break statement or the test-condition's result. Recall the last part of above
program, i.e.,

lf the loop-condition is still true outside the loop


that means break caused the loop termnination.
if not c t r < 5 :

print ("You lose :( \n The number was", number)

Infinite Loops and break Statement


which
Sometimes, programmers create infinite loops purposely by specifying an expression
some
always remain true, but for such purposely created infinite loops, they incòrporate
condition inside the loop-body on which they can break out of the loop using break statement

For instance, consider the following loop example:

a =2
NOTE
This will always remain True, hence, created infinite
while True: infinite lop; must be terminated For purposely.
there must be
print (a) through a break statement (or endless) loops,
reach break
a *= 2
a provision to
the body
statement from within
can De
if a>100: of the loop so that loop
break terminated.

9.7.4B The continue Statement


oth the
The continue statement is another jump statement like the break statement
from
statements skip ovér a part of the different

code. But the continue statement is somewnat mewhat


e loupho
break. Instead of
forcing termination, the continue statement forces the next iteratron
take place, skipping any code in
between.
OF CONTROOL
FLOW
;
Cropter

299
The
followingfigure (Fig. 9.8) explains the working of continue
statement:
while <test-condition> : <
rest of the for <var> in
statement.1 statements
in the
current iteration <sequence>
i f<condition> are
skipped and next statement 1
continuee iteration begins if <condition>
statement 2 continue
statement'3 statement 2
statement 4 statement 3
statement 4
In above loops, continue will cause
skipping of statements 2 & 3
in the current iteration and next
iteration will start.

Figure 9.8 The


working of a continue statement.

For the for loop, continue causes the next iteration by updating NOTE
the loop variable with the next value in sequence ; and for the
while loop, the program control passes to the conditional test The continue st¡tement skips
the rest of the loop statements
given at the top of the loop.
and causes the next iteration of
the loop to take place.
a = b = C = 0

for i in range (@, 3):


print ("Enter 2 numbers")
a = int (input( "Number 1:"))
b=int (input( "Number 2 :"))
ifb== 03
print ("\n The denominator cannot be. zero. Enter again !")
continue
else
C a//b

print ("Ouotient =", c)

ample run of above code is shown below:


Enter 2 numbers
Number 15 *************..
..At this point continueforced
next iteration to take place.
Number 2:0.
The denomi !
nator cannot be zero. Enter againn
Enter 2 numbers
Number 1 5
Number 2 : 2
Quotient =2
Enter 2 numbers
Number 1 6
Number 2 2
Quotient= 3
COMPUTER SCIENCE WITH PyT
300 N - K

abandon iteration of a loop prematurely.


Both the staten
Sometimes you need to
continue can help in that
but in different situations : statement break to termi eak and
the current iteration lo l Pend
iterations of the loop ;
and continue to terminate just loop will ding
with rest of the iterations.
contimue
Following program illustrates the ditference in working of break and continue stats
atements.

continue statements
9.17 to illustrate the difference between break and
Program
break' produces output as:")
print ("The loop with '
rogram
for i (1,11):
in range
if i%3 ==0
break
else
print (i)

print ("The loop with continue ' produces output as:")


'

for i in range (1,11):


if i%3 ==0 :
continue
else
print (i)
The output produced by above program is:

The 10op with 'break' produces output as :

1 because the loop terminated with break


2 when condition i % 3 became true with i = 3. (Loop terminated all pending iterations)

The l0op with 'continue ' produces output as :


1

only the values divisible by 3 are missing as the loop


simply moved to next iteration with continue when
condition i % 3 became true.
(Only the iterations wtihi % 3 == 0 are
8
terminated; next iterations are performed as it is)
10
use

Though, continue is one prominent jump statement, however, exp discourage its
riate useof
r , experts
whenever possible. Rather, code can be made more comprehensible by the approp
if/else.
9.7.5 Loop else Statement p-else clause.

Now that you know how break statement works, we can now talk about
details. As mentioned earlier, the else clause of a Python loop execu
1oO a s executed
thehloop rm i tor

cutes when
normally, i.e., when test-condition results into false for a while loop or for
the last value in the ioo
sequence; not when the break statement terminates tu 0 U S e s . Noticet h a
Before we proceed, have a look at the syntax of Python loops along with eise f o r

the else clause of a


loop appears at the same indentation as that of loop keywo
CONTROL

FLOW
OF
301
o
C h o p l e r 9 : F l O

Complete syntax
tax of Python loops along with else clause is as
given below:
Can evariable> in <sequence> while <test condition>
statement1
statement1
statement2
statement2

else: else:
statement(s) statement(s)
ig. 9.9)
(Fig. 9.9) iillustrates the difference in working of these loops in the absence and
Following figure
else clauses.
presence
of loop

element> in <sequence> Done while <test expression> false


for

next element true

statement statement -

statement statement
statement statement-
Body-of-
the-loop
Body-of- suite
statement
the-loop statement
Suite

statement
Statements statement Statements
Outside the l0op statement outside the loop statement

(a) Control flow in Python loops the absence of loop-else change

Done while <test expression false


for <element> in <sequence

Loop else
Loop else
next element true
suite
suite
statement statement
statement statement
statement: statement statement statement
statement+ statement
statement statement
Body-of--
Body-of.- the-loop
thSuie-oop
te suite statement statement
statement statement

oulStsiadetement s statement
the lo0p statement Statements

statement
outside the loop statement

of loop-else clause.
() Control flow in Python loops in the presence
else clauses.
Figure 9.9 of
Working Loops with or without
Python
APUTER SCIENCE WITH
302 PYTHO
HON
the Python Loops with or
Let understand the working of
us NOTE
without else clause
with the help of code examples..
The loop-else suite exe
(1, 4) only. in the
executes
for a in range case
termination of loop. of norn
print ("Element is", end
=
'

') ormal
print (a)
else
print ("Ending loop after printing all elements of sequence")

The above will give the following output:

The output produced by for This line is printèd because the else clause of
loop. Notice for loop executed Element is 1 given for loop executed when the for loop was
Element is 2 terminating, normaly.
for three values of a 1. 2, 3
- -

Element is 3

Ending 1oop after printing all elements of sequence.

Now consider the same loop as above but with a break statement:

for a in range (1, 4):


The break statentent will execute when a %2
if a % 2 == 0
is zero i.e., when a has the value as 2
break
p r i n t ("Element is", end = " ')

print (a)
else:
print ("Ending loop after printing all elements of sequence")

Now the output is Notice that for a = 2, the break got executed and loop terminated.

Hence just one element got printed (for a


= 1).
Element i s 1 As break terminated the loop, the else clause also did not execute,
so no line after the printing of elements.

The else clause works identically in while loop, i.e., executes if the test-condition goes false a
not in case of break statement's
execution. "

some
Now try predicting output for following code, which is similar to above code but order ors
statements have changed. Carefully notice the position of else too.
for a in range (1, 4):
print ("Element is", end = ' ')
print (a)
if a% 2==0:
break
else:
print ("Ending loop after printing all elements of sequence i n a b o v e

You are right. So smart This code does not have loop-else suite. i
you are, .
u s e with

code is part of if-else, not


loop-else. Now consider following program that Uses
a while loop. .
FLOW OF CONTROL

Chope
303
71 .Droaram to input some numoers repeatedly and print their
8
9.18
t o enter (normal termination) or sum.
The program ends when the users say no
mor program aborts when the number entered is less than zero.
rogram
Count = Sum = 0

ans = 'y

while ans=='y:

num int( input ( "Enter number:") )


if num < 0: - Body-of-the loop suite

print ("Number entered is below zero.


break
Aborting! ")
Sum = S u m + num

count count+1
ans input( "Want to enter more numbers? (y/n)..")
else loop-else suite
print ("You entered" count, "numbers so far .")|
,

print ("Sum of numbers entered is", sum)


This statement is outside the loop
Enter number: 3
want to enter more numbers? (y/n). .y
Enter number: 4
want to enter more numbers? (y/n)..y
Enter number: 5
Want to enter more numbers? (y/n)..n Result ofelse clause. Loop terminated
You entered 3 numbers so. far. normally
Sum of numbers entered is 12.
== RESTART==
=<<<==ss======<=<==:*S==
Enter number :
2
Want to enter more numbers? (y/n). .y
Enternumber: -3 No execution ofelse elause. Loop
Number enttered is below zero. Aborting! termingted because of break statement
Sum of numbers entered is 2

)9.19 Program to input anumber and- test if it is aprime number.


rogram num int (input ("Enter number: "))
lim = int (num/2) + 1

for i in range (2, 1im): .


rem = num % i

i f rem == 0: Enter number :7

print(num, "is rnot a prime number") 7.is a prime number


break
else: Enter number :49
number
49 is n o t a prime
print(num, "is a prime number")
304 COMPUTER SCIENCE WITH
PYTHOHON

Sometimes the is not entered at all, reason being empty sequence in a


loop
before entering in the while loop. In these cases the bod
for loop theor
test-condition's result as false
but loop-else clause will still be
executed.
loop is not executed
the same.
Consider following code examples illustrating
while ( 3 4) Body of the loop will not be executed
print ("in the loop") (condition is false) but else clause will

else:

print ("exiting from while loop")

The above code will print the result of execution of while loop's else clause, i.e..

exiting from while loop

Consider another loop - this time a for loop with empty sequence.

for a in range (10, 1): NOTE


Body of the loop will not be
print ("in the loop") executed (empty sequence)
The else clause of Python
else: but else clause wil loops
works in the same manner. That
print ("exiting from for loop") is, it gets executed when the
loop is terminating normally -
The above code will print the result of execution of for loop's
after the last element of
else clause, i.e., sequence in for loop and when
the test-condition becomesfalse
exiting from for loop in while loop.

9.7.6 Nested Loops


A loop may contain another loop in its body. This form of a loop is called nested loop. Butin a
nested loop, the inner loop must terminate before the outer loop. The following is an exampleof
a nested loop, where a for loop is nested within another for loop.

To ssee for i in range(1, 6)


Nested loop
in action
for j in range (1, i): end = ' 'at the end to cause

' < printing at same line


print ("*" , end =
')
1ine.
print () # to cause printing from next

The output produced by above code is


Scan
QR Code *

* *

* *

3 and The
4.
The inner for loop is executed for each value of i. The variable i takes values 1, 2,
values l, atse for
inner loop is executed once for i =1 according to sequence in inner loop range (y \
as 1, there is just one element 1 in range (1, 1) thus j iterates for one value, 1.e, 1),
(two elements in sequence range(1, i), thrice for i = 3 and four times for i=* valueo f

the
While working with nested loops, you need to understand one thing and that is,
ng i n t e r r u p t e d

outer loop variable will change only after the inner loop is completely finished (o
CONTROL

OF
Chopter

g:
FlOw
FLOW
305
To understand this, consider the
tollowing code fragment
1n range (5, 10, 4)
forouter for inner inrange(1, outer, 2):
print (outer, inner)

The
above code
will roduce the output as :

The output produced when the outer = 5


51
5
91
93 The output produced when the outer = 9
95
97
below:
Seethe explanation
5
uter s
value
in
change inner loop got over after value 3's iteration

outer's value 3
change in
inner loop got over after value 7's iteration
7
Check Point

9.3
Let us understand how the control in nested
1. What are iteration statements ? Name the
moves a loop
with the help of one more
example:
iteration statements provided by Python.
2. What the two
are
categories of Python for a in range(3)
loops
3. What is the for b in range(5, 7) :
use ofrange() function ?
What would print ("for a =", a, "b now is", b)
range(3, 13) return ?
4.What is the
output of the following The above nested loop will produce following output:
code fragment?
for a in "abcde"
print for a = 0 b now is 5
(a, '+', end =
'

')
What is the
code fragment?output
of the following for a = 0 b now is 6
for i in Inner loop

pass
range (0, 10): for a = 1 b now is 5
iterations
print (i) for a = 1 b now i s 6
Why does "Hello" not
for i in print even once
nce? for a = 2 b now is 5
range(10,
print ("Hello") 1) for a = 2 b now is 6
Mnat is
the
Tor output of following code
ain range Outer loop
for bin (2, 7) iterations

print (range(1,
Notice. for each outer loop iteration,
a) inner loop iterutes twice

print () #, end '


=
")
306 cOMPUTER SCIENCE WITH

For the outer loop, firstly a takes the value as 0 and for a =0, inner loop iterates
PYTHON-
PYTHON
terates as it is
outer for's loop-body. part ot
for a = 0, the inner loop will iterate twice for values
b = 5 and b =6

hence the first two lines of output given above are produced for the first iteration at.
loop (a =0; which involves two iterations of inner loop) Outer
w h e n a takes the next value in sequence, the inner will again iterate two times with d
5 and 6 for b. values
Thus we see, that for each iteration of outer loop, inner loop iterates twice for valuesb=5.
and
b=6.

Consider some more example and try understandingthe


C h e c kP o i n t

functioning based on above lines.


9.3 ntd..)
for a in range (3)
8. Write a for locp chat displays the even for b in range(5,7):
numbers from 51 to 60. print ("* ", end =' ')
9. Suggest a situation where an empty
print ()
loop is useful.
10. What is the similarity and difference The output produced would be
between for and while loop ?
11. Why is while loop called an entry
controlled loop ?
12. If the test-expression of a while loop
evaluates to false in the beginning of
the loop, even before entering in to the
Consider another nested loop:
loop for a in range(3) :
(a) how many times is the loop
for b in range(5,8):
executed? noticeend=" "at

(b) how many times is the loop-else


print ("* ", end =' ')
the end ofprnt
clause executed ? print ()
13. What will be the output of following
code:
The output produced would be:
while (6 + 2 > 8) * *

print ("Gotcha!") ***

else:
print ("Going out!")
14. What is the output produced by
The break Statement in a Nested LooOP i twil
following loop? h e break
for a in (2, 7): If the break statement appe it zinatethe
That is,
for b in (1, a) : terminate the very loop it is in. tern
print (b, end = ' ')
then it
will 25i t
as
statement is inside the inner loop will continue
print () inner loop only and the outer. loop outer.
then s badyi

15. What is the significance of break and the break statement is in outer loop, outer
loop
u t e r
l o o p [

continue statements? of
terminated. Since inner loop is part
16. Can a single break statement in an inner Will also not execute just like other statement
loop terminate all the nested loops ?
body.
CONTROL
FLOW OF
9:
C h o p t e r

307
Following program illustrates this.
ogram illu Notice that break will
progress. terminate the inner loop only while
outer loop will;
as
per its routine.
the
90 Program that searches for prime numbers from 15 through 25.

for num in range(15,25):


rogram
for i in range(2, num)
if num % i == 0:
#to determine factors
terminate the j num/i
will
This break
innerfor
loop only print ("Found a factor(", i,") for", num)
break #need not continue factor found
-
else: #else part of the inner
loop
print (num, "is a prime number")

Theoutput produced by abOve program will be:

FOund a factor( 3 ) for 15


Found a factor( 2 ) for 16
17 is a prime number
Found a factor( 2 ) for 18
19 is a prime number
Found a factor ( 2 ) for 20
Found a factor( 3 ) for 21
Found a factor( 2 for 22
23 is a prime number
Found a factor ( 2) for 24

More examples of nested loops and other


the end of this
simple loops you'll find in solved problems given at
chapter.
This
brings us to the end of this
chapter. Let us
quickly revise what we have learnt so far.

PiP PYTHON LoOPS


Progress In Python 9.2
This gress in thon' session works on the objective of Python loops practice.
Carefully ead
read the instruction and then carry out the problem. Once through with conceptual
stions, you can move on to practicing programming problems.

lease check the practical component-book - Progress in Computer

cience with Python and fill it there in priP 9.2 under Chapter 9 after
practically doing it on the computer.
COMPUTER IENCE WITH
308 PYTHON
LET US REVISE
to perform any kind of action
the instructions given to the computer
Statenments
are
empty statement, single statement and
conm
be on one
of these ypes:
Python statements
statement
can

is the statement that does nothing. Python offers pass as em


statement as empty statement atement.
Anempty statement.
s t a t e m e n t forms a simple
Single executable executed as a unit.
a group of statements
statement represents
A compound indented body below the header
has a header and an r

Every compound statement of Python while statement etc.


Some examples of compound
statements are:
if statement,
can be in three ways: sequentially (the sequence construe
onstruct), selectively t
The flow of control in a program
iteration construct). the
selection construct), and iteratively (the
The sequence
get executed sequentially.
construct means statements
a condition-test.
execution of statement(s) depending upon
The selection construct means the
mean repetition of a set-of-statements depending upon
a condition.d
T h e iteration (looping) constructs on-test.
forms if.else and if.elif.else.
provides one selection statement if in many
-

Python
The if.else statement tests an expression and depending upon its truth value one ofthe two sets-of-action is executed,

an if statement can have another if statement.


The if-else statement can be nested also i.e.,
A sequence is a succession of values bound together by a single name. Some Python sequences are strinas. lict and

tuples
The range( ) function generates a sequence of list ype.

The statements that allow of instructions to be performed repeatedly are iteration statements.
a set
The for is a counting loop and while is a conditionalloop.
Python provides two looping constructs -for and while.
over entry in the loop in the form of test condition.
The while loop is an entry-controlled loop as it has a control
is executed in the end of the loop only when lop
Loops in Python can have else clause too. The else clause of loop
a

terminates normally.
control passes over to the statement following me
The break statenent can terminate a loop immediately and the
statement containing break.
I n nested loops, a break terminates the very loop it appears in.
the
statemenis un
The continue statement abandons the current iteration of the loop by skipping over the rest ofthe
loop-body. It immediately transfers control to the beginning of the next iteration of the loop.

)bjective Type Questions


OTQs
Multiple Choice Questions
execution in tne
3. The order of
1. In a Python program, a control structure statement Construct

as,
(a) directs the order of execution of the top to bottom, is known
statements in the program (6) repetition
(a) selection
(b) dictates what happens before the program (d) flow
starts and after it terminates
(c) sequence construct allows to e

4. The upo
()defines program-specific data structures be ecuted,
depending
statements to
(d) manages the input and output of control result of a condition.
characters (b) repetition
(a) selection
2. An empty/null statement in Python is (d) flow
(C) sequence
(a) go (b) pass (c) over (d)
CONTROL
OF
FLOW
Jar 9:
Cnaprer 309
construct repeats a set of statements
of times
12.If the user inputs 2<ENTER>, what does the
5.The
pecified number or as long as
a following code snippet print ?
condition 1S true.
x float (input () )
=

(b) repetition
(a) selection

if(x == 1):
(d) flow
( ) s e q u e n c e

print("Yes")
following statements will make a elif (x
Which ofthe. >= 2):
6.s e l e c t i o n c o n s t r u c t ?
print("Maybe")
(6) if-else (c) for (d) while else:
(a) if

Vhich ofthe following statemernts will make a print ("No")


7 repetition construct ? (a) Yes (6) No (c) Maybe
(a) if (b) if-else (c) for (d) while (d) Nothing is printed () Error
which of the following will create a Consider the following
8.In Python,
a compound statement ?
code segment for the
block in questions 13 -177
(a) colon

at a lower,
a int(input("Enter an integer: "))
(b) statements indented same level
b int(input("Enter an integer: "))
) indentation in any form if a <= 0:
b =b+1
9.What signifies the end of a statement block or
else:
suite in Python ?
a = a +1
a) A comment (b)} i f a >0 and b > 0:
)end
print("w")
(d) A line that is indented less than the
elifa> 0:
previous line
print("x")
10.Which one of the following if statements will
i fb> 0:
not execute successfully ?
print("Y")
() if (1, 2): (b) if (1, 2)
else:
print('foo') print(foo') print("z")
() if (1, 2): (d) if (1): 13. What letters will be printed if the user enters 0
print('foo') print(" foo') for a and 0 for b?
11, What does
the following Python (a) Only W (b) Only X ()Only YY
display ? program
(d) W and X (e) W, X and Y
X = 3
14. What letters will be printed if the user enters 1
ifx== 0: for a and 1 for b ?
print ("Am I here? ", end '
=
') (a) W and X (6) W and Y (¢) X and Y
elifx== 3: (d) X andZ (d) W, X and Y
print("Or here?", end =
"

") 15. What letters will be printed if the user enters 1


else
for a and -1 for b?
pass
print ("Or over (a) W and X (b) X and Y (c) Y and Z
here?") (d) X and Z () W and Z
a) Am I here ?
) Am I (6) Orhere? 16. What letters will be printed if the user enters 1
here? Orhere? for a and 0 for b ?
) Or here?
Or over here ? (a) W and X (b) X and Y (c) Y and Z
e) Am I
here? Or over here ? (d) X and1z (e)Wand Z
COMPUTER SCIENCE WITH
WITH PYTHON-
PYTu
310
if the user enters -1: How many times will this
oop run ?
17. What letters will be printed (a) 5 (6) 0
for a and -1 for b ?
Y (c) infinite (d) Error
(e) Only W (b) Only X () Only
(d) Only Zz (e) No letters are printed 28. Consider the loop given below
when the function
fori in range(10, 5,-3)
18. What values are generated
is executed? print(i)
range(6, 0, -2)
(a) [4, 2] (b) [4, 2, 0] () [6, 4,2] How many times will this loop run?

(d) [6, 4, 2, 01 (e) [6, 4, 2, 0, -2] (a) 3 6)2 (c) 1


in
(d) Infinite
19. Which of the following is not a valid loop 29. Consider the loop given below
Python? for i in
range(3)
() for (b) while
pass
(c) do-while (d) if-else
What will be the final value ofi after this loop2
20. Which of the following statement(s)
terminate the whole loop and proceed to the
will (a) 0 (6) 1 )2 (d) 3
30. Consider the loop given below:
statement following the loop ?
(6) break
for i in range(7, 4, -2)
(a) pass
break
(c) continue (d) goto
21. Which of the following statement(s) will What will be the final value of i after this loop?
terminate only the current pass of the loop and (a) 4 (b) 5 7 (d)-2
proceed with the next iteration of the loop? 31. In for a in. :, the blank can be filled with
(a) pass (b) break
(a) an iterable sequence
(C) continue (d) goto (b) a range() function
22. Function range(3) is equivalent to
(c) a single value (d) an expression
() range(1, 3) (b) range(0, 3)
32. Which of the following are entry controlled
(c) range(0, 3, 1) (d) range(1, 3, 0)
23. Function range(3)
loops?
will yield an
iteratable (a) if (b) if-else (c) for (d) while
sequence like .
De
33. Consider the loop given below. What will
() [o, 1, 2] (b) [O, 1, 2, 31
() [1, 2, 3] () [0, 21 the final value of i after the loop?
24. Function ran e(0, 5, 2) will yield for i in range (10)
on
iterable
sequence like break
(a) [0, 2, 4] (b) [1, 3, 5] (a) 10 (b)0 (c) Error (d)9
(c) [0, 1, 2, 5] (d) [O, 5, 2] 34. The else statement can be a part of
25. Function range(10, 5, -2) will
yield an iterable statement in Python.
sequence like
(a) if (b) def () while (d) for
(a) [10, 8, 6] (b) 19,7, 5] J u m p statements
35. Which of the
() [6, 8, 10] (d) [5, 7, 9 following are
26. Function range(10, 5, 2) will yield (a) i if (6) break
an
iterable (c) while (d) continue
sequence like
36. Consider the following code segmen
(b) [10, 8, 6]
) 12, 5, 8] 4) 8, 5, 2 for i in range (2, 4):
27. Consider the loop given below print(i)
it exec
What inted when
for i in range(-5) : values(s) are ()2and3
(a) 2 3
print(i) and 4
(d) 3 and 4 () 2, 3
CONTROL
FLOW OF
er9:

code runs,
311
the following how many
When *
2" executed ?
(d) for j in
range (10, 5):
the line "x x
=
37.
is
times
X=1
print("X")
while (x< 20 ): (e) for j in
range(10, 5, -1):
X = x * 2 print("X")
42. What is the
(4) 2 ()5 (c) 19 (d) 4 () 32 output produced when this code
executes?
is the output when this code executes?
38.What a = 0
X = 1
for i in
while (x<=5): range(4,8):
if i%2 == 0:
x+1
a a+ i
print (x)
print(a)
(a) 6 (b) 1 4 (b) 8
(c) 10 (d) 18
(d) 5 (e) no output
(C)4 43. Which of the
9. How many times does the following code following code segments contain
an
example a nested
of
loopp?
execute?
X = 1
(a) for i in range(10):
print(i)
while (x <= 5): for j in range(10):
x+1
print(j)
print (x) (b) for i in
(a) 6 (b) 1
range(10)
print(i)
c)4 (d) 5 (e) infinite for j in range(10):
40. What is the output produced when this code print (3)
executes?
i= 1
(c) for i in range(10):
print(i)
while (i <= 7): while i < 20:
i*=2 print(i)
print (i) i i +1
(a) 8 (b) 16 (c) 4 (d) 14 (d) for i in range(10):
e)no output print(i)
41. while i 20
Consider the following loop:
print(i)
j 10
while j = 5: Fill in the Blanks
statement forms the selection
print("X") 1. The
j j-1 construct in Python.

Which
the
of the
following loops for will gener 2. The
statement is a do nothing statement

same output as the in Pythorn.


loopsshown previously ? and
statements for the
tor j in 3. The
range(-1, -5, -1): construct in Python.
repetition
print("X") that govern the flow of control
(6) for j in 4. Three constructs
range (0, 5): are
and

print("X") 5. In Python,, defines a block of statements.


for in range (10, -1, -2): 6. An
has less number of
statement
successive ifs.
print("X") conditional checks than two
COMPUTER SCIENCE WITH
PYTH
312 AON-
2. A for loop is termed as a detorn :
7. The _operator tests if
contained in a sequence or not.
a given value is
T h e wlhile loop is an exit controlled lo
minable loo
and oop.
8. The two membership operators are ,

4. The range()creates an iterab sequer


5 The for loop can also tests a condition
9. An iteration refers to one repetition of a .

executing the loop-body. dition befoe


loop iterates over a sequence.
10. The ir s t a t e m e n t can have an elsa
6. Oniy
11. The loop tests a condition before
7. A loop can also take an else clause.
clause
executing the body-of-the-loop.
clause can occur with an if as well 8. The else clause of a loop gets executed.
12. The
as with loops. when a break statement terminates it. only
13. The block of a loop gets executed when 9. An loop with an else clause executes
ts else
a loop ends normally. clauseonly when the loop terminates normall
14. The else block of a loop will not
get execute
statement has terminated the loop.
10, A loop with an else clause cannot have abresk
a. statement.
15. The statement terminates the execution
11, A continue statement can replace a break
of the whole loop.
statement.
16. The statement terminates only a single ;
12. For a for loop, an equivalent while loop can
iteration of the loop.
always be written.
17. The break and continue statements, together
are called statements. 13. For a while loop, an equivalent for loop can
18. In a nested loop, a break statement inside the always be written.
inner loop, will terminate the . loop only. 14, The function
range() can only be used in for loops.
True/False Questions 15. An if-elif-else statement is equivalent to a
nested-if statement.
1, An if-else tests less number of conditions than:
two successive ifs.

NOTE: Answers for OTas are given at the end of the book.

Solved Problems
1. What is a statement ? What is the significance of an empty statement ?
Solution. A statement is an
instruction given to the computer to
An empty statement is useful in situations
perform any kind of actuo
not. I
where the code requires a statement but logic
fill these two
requirements simultaneously, empty statement is used. ao
Python offers pass statement as an empty statement.
2. f you are asked to label the Python loops as determinable or non-determinable, which label woula
which loop ? Justify your yo o
answer
Solution. The 'for loop' can be labelled as deterninable its iterations can
determined before-hand as the size of the loop as number of its 1ca
sequence, it is operating upon.
The 'while loop' can be labelled as c a n n o t

be determined before-hand. Its iterations


non-determinable loop, as its number of iterannot
determined before-hand. depend upon the result of a test-conditiOn, w
3 There are two types of else clauses in Python. What are these tuwo types of else clause
Solution. The two types of Python else clauses are
(a) else in an if statement
(b) else in a
loop statement
FLOW
OF CONTROL

Chopth
9: 313
s1Ge
clause of if statement is executed when the condition of the if
Of aan
The else statement results into
clause of a loop is executed when the loop is false.
The terminating normally i.e., when
flse for a while loop or when the for loop has executed for the last value in its test-condition
sequence.
Use the thon range( ) unction to create the follorwing list: [7, 3, -1, -5]

Solution.
range (7, -6, -4)

.ldentify and correct the problenm with following code :


.
countdown 10 #Count from 10 down to 1
whilecountdown0:
print (countdown, end = ' ')

countdown 1
print ("Finally. ")
Colbstion. It is an infinite loop. The reason being, in the above while
expression loop, there is an
countdown -1, which subtracts 1 from value of countdown BUT this statement is not updating the
loop variable countdown, hence loop variable countdown always remains unchanged and hence it
is an infinite loop.
The solution to above problem will be replacement of countdown -1 with following statement in
thebody of while loop:
countdown = countdown 1
Now the while loop's variable will be updated in every iteration and hence
loop will be a finite loop
6. Following code is meant to be an interactive grade calculation scriptfor an entrance test that converts from a
percentage into a letter grade :
90 and above is At, 80-90 is A, 60-80 is A-, and everything below is fal.
The program should prompt the user 100 times for grades. Unfortunatety, the program was written by a
terrible coder (me :/ ), so there are numerous bugs in the code. Find all the bugs and fix them.
For i :
range (1 . .
100)
grade == float (input( "what\'s the grade percentage ?" ))
if grade> 90
print ("That's an A+!")
if 80 grade > 90:
print ("" "An A is really good!" " ")

elsif 60 < grade:


print (You got an A-!)
else grade < 60:
print ("Sorry, you need an A- to qualify! ")
o n . The corrected code is given below, with corrections marked in colour.

for i in range (e, 100)


the grade percentage ?)
8Pade float (input ( "What's
if grade >= 90
print (That's an A+! ")
if 80 <= grade < 90:
also OK
print ("An A is really good!") # although triple-quoted string is
elif 60 <= grade :
print ("You got an A-!")
else grade < 60
print ("Sorry, you need an A- to qualify! ")
cOMPUTER SCIENCE WITH
PYTH
314 PYTHON -
? (b)
7. What is the output of follorwing code name ==
if (4 5 == 10)
while name= "end"
print ("TRUE")
name input( "Enter name
end to
(end to evis
exit)")
else i f name == "end'"
print ("FALSE")
pass
print ("TRUE")
print ("Hello", name)
Solution. FALSE
else:
TRUE
print ("Wasn't it fun ")
8. Following code contains an endless loop. Could you
? solution. Solution.
find out why Suggest a

n 10 Code (a) will print


answer = 1 for input ()
while (n>0 ) : Hello Jacob
answer answer + n ** 2

n = n +1
for input ii)
Hello 12345
print (answer)
Solution. For a while loop to terminate, it is ; for input (ii)
necessary that its condition becomes false at : Hello ENDD
one point. But in the above code, the for input (iv)
test-condition of while loop will never become
no output will be printed
false, because the condition is n>0 and n is;
always incrementing ; thus n will always Code (b) will print
remain> 0. Hence it will repeat endlessly.
for input ()
There are two possible solutions:
Hello Jacob
() change the condition to some reachable
for input (i)
limit (as per update expression) e.g,
Hello 12345
while (n< 100)
for input (ii)
(ii) change the updation equation of loop
Hello END
variable so that it makes the condition
false at some point of time, e.g., for input (iv)
Hello end
while (n >0): Wasn't it fun ?
n = n1 d
10. Write code to add the odd numbers up
Python
9. Consider below given two code fragments. What (and including) a given value N and print the resi
will be their outputs if the inputs are entered in the Solution.
given order are (i) Jacob' (i)'12345' (ii) 'END' N int (input ('Enter number))
(iv) 'end' ? Sum =

(a) i =1
name ="" while i <= N :
while True Sum = Sum + 1

name input( "Enter name ('end to exit):") i = i + 2


i f name == "end"
print (sum)
break
I1. Consider the following Python progran
print ("Hello", name)
else
N =int(input ("Enter N:"))
print ("Wasn't it fun ?") i 1
FLOW OF CONTROL

315
Sum = 6 The output
< N:
produced by above program will be:
whilei
== 0: Enter 1st number: 45.2
i fi s 2 Enter 2nd number: 66
Sum = Sum + i
Enter 3rd number:
i i+1 11.56
The largest number is 66.0
print (sum)

lhc atutout when


when the
input value is 5?14. Write
Whatisthe output
a
program to input a 6 digit number and
when the input value is 0 2 divide it into three 2
) What is the output digit numbers.
Solution. (a) 6 (b) 0 Solution.
num
int (input("Enter a 6 digit number "))
Cansiderthe following
Python program, intended to if num <
100000 or num > 999999:
calculatefactorials
print("Please enter a 6 digit number")
("Enter number") ) else:
number int (input
number,1 n1 num % 100
n,
result =

n: int1 = num //100


WhileTrue or
result *
n n2 int1% 100
result
n n-1 int2 int1 // 100
factorial = resultt n3 int2 %100
print ("factorial of ", number, "is", factorial) print("Three 2-digit numbers are:", n1, n2, n3)

(a) Whathappens when the user enters a value of5? Enter a 6 digit number: 678923
Three 2-digit numbers are: 23 89 67
(b) How would you fix this program ?
Solution. The problem is that the 15. Write a program to input a number and then
program print
will repeat infinitely. its first amd last digit raised to the length of the
Theproblem lies with the condition of while number (the number of digits in the number is the
loop this condition will never go false. length of the number).
Correct condition will be any of these: Solution.
while n import math

Ur
num
int(input ("Enter a number: "))
while n> 0: ln len( str(num)) # length of the number
lst = num % 10
fst num // math.pow(10, 1n-1)
e &program to input three numbers and display
the print("Length of given number", num, "is", ln)
largest I smallest number.
print("The first digit is "', fst)
Solution. print("The last digit is ", lst)
float (input ("Enter 1st number: ")) print("First digit raised to the length: " , \

float math.pow(fst, In))


num3 (input (" Enter 2nd number:)
if
float input ("Enter 3rd number: "))
print("Last digit raised to the length:",\
math.pow(lst, In)))
(numl > num2) and (num1> num3):
eliflargest
(num2 num
num? Enter a number : 326868
11) and (num2> num3): Length of given number 326868 is 6
largest =num2 The first digit is 3.0
else:
The last digit is 8
largest =num3 First digit raised to the length: 729.0
print ("The larg
largest Last digit raised to the length 262144.0
number is", largest)
316 COMPUTER SCIENCE WITH
PYTHON
16. Write a program to find lowest and second lowest number from the 10 numbers input.

Solution.
#to find lowest and second lowest integer from 1e integers
small smaller = 0

for i in range(10):
n int(input ("Enter number : "))
if i == 0 : # first number read
small = n
elif i == 1 # second number read
i fn small:
smaller = n
else:
Smaller = small
small =n
else: # for every integer read 3rd integer onwards
i fn <smaller
small = smaller
smaller = n Sample Run
elif n < small
The lowest number is: 6
small = n
The second lowest number is : 4
print("The lowest number is: ", smaller)
print("The second lowest number is : ", small)
The sample run of above program (from the ten input numbers as

-6, 13, 20,-3, 15, 18, 99,4, 11, 23) has been given above.
17. Number Guessing Game This program generates a random number between 1 and 100 and continuously
asks the user to guess the number, giving hints along the way.
Solution.
import random
secretNum = random.randint (1, 100) #generate a random integer between [1 100
guessNumString = int(input ("Guess a number between 1 and 100 inclusive: "))

while guessNum != secretNum


i f guessNum < secretNum
print ("Your guess is too low.")
else:
print ("Your guess is too high.")
guessNum = int(input ( "Guess a number between 1 and 100 inclusive: "))

print ("Congratulations! You guessed the number correctly.")


18. Write a Python script to print Fibonaci series fivst 20 elements. Some initial elements ofa Fibonacci serie are

1 1 2 3 5 8...
Solution. first = e
second = 1

print (first)
print (second)
for a in range(1, 19)
third first + second
print (third)
first, second second, third
OF CONTROL

Chopte
9:
FLOW
317
+hon script to read an integer 1 0 0 and: 23. Write a program to input a number and calculate its
Python
Write a
19. reverse the n u m b e r . double factorial.
Solution. (For an even integer n, the double factorial is the
int(input( "Enter an integer (1000) :")) product of all even positive integers less than or
num

tnum = num equal to n. For an odd integer p, the double factorial


reverse =e is the product of all odd positive integers less than or
while tnum equal to p.)
tnum % 10
digit = Solution.
of division
#take out int part
tnum int(tnum/10)
num int (input("Enter a number "))
reverse = reverse * 10 + digit fac 1
for i in range(num, 0, -2):
print ("Reverse of",
num "is", reverse)
fac *= i
to
20, Write a Python script generate
divisors ofa number. print(num, "!! is *", fac)
Solution.
num int(input("Enter an integer:" )) Enter a number: 7
mid = num /2 7!! is: 105
print ("The divisors of" num, "are :")
for a in range (2, mid + 1) Enter a number:6
if num % a == 0 : 6!! is : 48
print (a, end = ' ')

else 24. Numbers in the form 2"- 1 are called Mersenne


print ("-End-") Numbers, e.g
21. Input three angles and determine if they forma 2-1-1,22-1-3,23 -1=7.
triangle or not. Write a Python script that displays first ten
Solution. Mersenne numbers.
#check triangle from angles Solution.
anglel = angle2 = angle3 = e
#program to print mersenne numbers
angle1 = float(input("Enter angle 1 : "))
print("First 10 Mersenne numbers are: ")
angle2 float (input("Enter angle 2 : "))
for a in range(1, 11):
angle3 float (input("Enter angle 3: "))
=
mersnum = 2 ** a 1
if
(angle1 + angle2 angle3) + == 180: print(mersnum, end = " ")

print("Angles form a triangle. ")


else: print()
print("Angles do not form a triangle.") First 10 Mersenne numbers are :
22 Write a and n, 13 7 15 31 63 127 255 511 1023
program to
input two integers x
compute
x" using loop.
a
25. Write Python script to print thefollowing pattern:
Solution.
*
1
Int(input ("Enter a positive number(x): "))
int(input
power 1
("Enter the power (n): * 13
13 5
tor a in
range(n):
power power*x
13 5 7

Solution.
X,"to the power", n, "is", power) for a in range(3, 10, 2) :
Enter a for b in range(1, a, 2)
positive
number (x): 7
Enter the print (b, end = ' ')

7 to the power (n): 3


power 3 is 343 print ()
COMPUTER CIENCE WITH
PYTHON
318
numbers also, are called Mersenne Prime numbers. Make modifications in
Make modic
26. Mersenne numbers
that are prime Prime' next to the Mersenne Primenunmher
numbers. Also,
that it also displays this
previous question's Python script
so
Sample Run
numbers.
time print 20 Mersenne
(With first 10 Mersenne numbers)
Solution.
prime numbers 1 Prime
# program to print mersenne

Prime
for a in range(1, 21):
mersnum 2 ** a -1
7 Prime
1
15
mid int (mersnum / 2) +
31 Pri
for b in range (2, mid):
i f mersnum % b == e
63
127 Prime
print(mersnum)
255
break
511
else:
print(mersnum, "\tPrime")
1023

BMI ofa person after inputting its weight


in kgs and height in meters and then
27. Write a program to calculate
the Nutritional Status as per following table:
print
Nutritional Status WHO criteria BMI cut-off
<18.5
Underweight
Normal 18.5 24.9

Overweight 25 29.9

Obese 230

Solution.
weight_in_kg - float (input ("Enter weight in kg:"))
height_in_meter = float(input("Enter height in meters :"))
bmi =weight_in_kg/ ( height_in_meter height_in_meter)
print("BMI is: ", bmi, end = " ")

i fbmi « 18.5
print("... Underweight")
elifbmi < 25
print("... Normal")
elif bmi < 30 :
print(".. . Overweight")
else:
print("... Obese")
Write a program to find sum of the series: s=1+x+r2 + 3 . . t x " (Input the values of x and w
28.
Solution.
x =
float (input ( "Enter value of x :" ))
n int (input ( "Enter value of n (for x ** n) :"
)
for a in range(n + 1):
St x ** a

print ("Sum of first" , n , "terms:", s)


FLOW
OF
CONTROL
319
Chopter
9:

program.
to input the value of x and n and: for i in range(1, n):
Write a the series
if(n % i == 0):
29.
sum of
yrintthe1-X+r-x° summ = summ + i
+x* - . . . "
if (summ == n)

Solution.
print("The number", n, "is a Perfect number!")
value of x: ") )
x
int(input( "Enter else:
the power (n): ")) print("The number", n, " is not a Perfect number! ")

n= int (input("Enter
Enter number: 28
sign = +1
The number 28 is a Perfect number!
for a in range(n 1):
term = (X ** a ) * sign
32. Write a program to check if a given number is an
S t term Armstrong number or not.
sign *= -1
(Note. Ifa 3 digit number is equal to the sum of the cubes
print("Sum of first", n, "terms : ", s)
of its each digit, then it is an Armstrong Number.)
Enter value of x: 5 Solution.
Enter the power (n): 4
num int(input("Enter a 3 digit number: "))
Sum of first 4 terms 521
Summ = e

temp = num
30. Write a program to input the value of x and n and: while (temp > 0):
print the sum of the series digit temp % 10
2 **3
summ += digit
21 34! n! temp //= 10
i f (num == summ):
Solution.
x = int(input("Enter value of x: ")) print(num, "is an Armstrong number")
else:
n
S X
int(input ("Enter the power (n): "))
print(num, "is Not an Armstrong number")
# first term added
sign +1 Enter a 3 digit number: 407
for in
a
range (2, n + 1): 407 is an Armstrong number
f 1
for i in range(1, a+1) 33. Write a program to check if a given number is a
f *= i palindrome number or not.
term = ((x ** a) * sign ) / f
Solution. (A palindrome number's reversed
S+ term number is same as the number.)
sign *= 1
num int (input ("Enter number: "))
print("Sum of first", n, "terms " S)
wnum num # working number stores num initially
Enter value of x: 4 rev 0
Enter the while(wnum > 0):
power (n): 5
Or first 5 terms 3.466666666666667 dig = Wnum % 10
rev rev*10 + dig
31 Write a program to check ifa given number is a wnum = wnum / / 10

perfect number or not.


if(num == rev):

(Note. Aperfect number is a positive integer, which


print("Number", num, "is a palindrome! ")
S else:
equal to the sum of its divisors.) print("Number", num, "is not a palindrome! ")
Solution.
int(input("Enter
Summ mber: "))
Enter number: 67826
Number 67826 is not a palindrome!
320 COMPUTER SCIENCE WITH
PYTHON - X

34. Write a program to print Fibonacci series. 37. Write a program to design a dice throw.
Solution. Solution.
t int(input("How many terms ?(enter 2+ value): ")) import random
first e n =
int(input ("How many dice throws? "))
second = 1 for i in range(1, n+1)
print("\nFibonacci series is: ") print("Throw", i, ":",
random.randint (1, 6))
print(first, ",", second, end =", ") How many dice throws ? 5
for i in range(2, t): Throw 1 : 5
next first + second Throw 2 : 4
print(next, end=", ") Throw 3 : 5
first second Throw 4 : 3
second = next Throw 5 : 5

How many terms?( enter 2+ value): 8 38. Write a


program to implement a simple calculator
Fibonacci series is: for tuwo input numbers. Ofer choices through a menu.
0, 1, 1, 2, 3, 5, 8, 13,
Solution.
35. Write a
Python script to input numbers and
two
print("Enter 2 numbers below")
print their lcm (Least common multiple) and gcd
(greatest common divisor).
a
int(input("Enter number 1:"))
b int(input ("Enter number 2: "))
Solution. ch
x =
int(input( "Enter first number: ")) while ch < 5:
y =int(input ( "Enter second number: "))
if x > y:
print("Calculator Menu")
smaller =y print("1.Add")
else: print("2.Substract")
smaller = X print("3.Multiply")
for i in range(1, smaller +
1): print("4.Divide"))
if((x % i == 0) and (y % i == 0)): print("5.Exit")
hcf i
lcm = (x * y ) / hcf
# input choice
ch int (input ("Enter Choice(1-5) : ")
print("The H.C.F. of", X, "and", y, "is", hcf)
print("The L.C.M. of", X, "and", y, "is", lcm) if ch == 1:
C =a + b
36. Write a
Python script to calculate sum of following print("Sum = ",c)
series
elif ch == 2:
s=
(1)+(1+2)+(1+2 +3)+...+(1+2 +3+..+ n) C =a b
Solution. print("Difference = ",c)
Sum = O8
elif ch ==
3
n int (input ( "How many terms ?") ) C a * b

# added 2 to
because started with
n
2 print("Product = ", c)
for a in range(2, n+2)
elif ch == 4:
term = C a/ b
for b in range(1, a): print("Quotient = ",c)
term += b
elif ch == 5:
print ("Term", (a 1), ":", term)
sum + term break
print ("Sum of"', n, "terms is" else:
, sum)
print("Invalid Choice")
FLOW OF CONTROL

321
rager
Y:HOW

to yrint the following using a 40. Write a


W r i t e a p r o g r a m

program to print a pattern like:


nested loops):
single
loop(no 4321
432
43
111
1111
11111 Solution.
for i in
Solution. range(4):
for j in
n 1 range(4, i, -1):
for a in range (5) : print(j, end =" ")
print (n) else:
n = n * 10+1
print()

idelines to N CERT Q uestio ns


NCERT Chapter 6
1. What is the difference between else and elif construct of if statement ?
Ans. The else clause gets executed when the condition tested with if is false.
The elif clause tests another condition when
the condition with if is false.
2 What is the
purpose ) ? of range( function Given one
example.
Ans. The
range() function generates an iterable sequence using the arguments start,
ofrange() function. It is very handy and useful for the 'for' loops, which stop and stop
for looping require iterable sequence
an

.Diferentiate between break and continue statements


using exanmples.
Ans.Both the break and
continue statements are jump statements. When the
break statement gets
xecuted, it terminates its loop completely and the control reaches to the statement
following the loop. immediately
COntinue statement on the other
hand, terminates only the current iteration of the
Pang rest of the statements in the loop by
1oop after the continue body of the loop. The control resumes the next iteratiorn of the
4.What it is
statement.
an
infinite loop ? Give one example.
Thi niite loop is the one whose terminating condition is either missing or is not reachable.
the
.
Find the body-of-the-loop
keeps repeating endlessly in an infinite loop.
( a 110output of the
following program segments
while a > 100 (ii) for i in range (20, 30, 2):

print(a) print(i)
a- 2 (in) country = 'INDIA

(to)i =0, sum for i in country:


while i <9 = print(i)
if i% 4 == 0

Sum= Sum + ii
i i+2
print(sum)
COMPUTER SCIENCE WITH
PYTHON-
322
in range(1, 4)
:
(v) for x

for y in range(2, 5):


10:
if x *y >

break
print(x * y)

(vi) var 7
while var > e
print('Current variable
value:', var)
var var 1
i f var == 3:

break
else:
i f var == 6:

var = Var - 1

continue
print ("Good bye! ")
Ans.
I (iv) 12 (o)2
() 110 i) 20 (i)
108 22 N

106 24 D

104 26 I
102 28 A
8
6
9

(vi) Current variable value: 7

Current variable value: 5


Good bye!
Current variable value : 4

NCERT Programming Exercises


1. Write a program that takes the nanme and age of the user as input and displays a message whether the 1sea

eligible to apply for a driving license or not. (the eligible age is 18 years).
Ans.
name input("Enter name ")
age int(input("Enter age "))
if age =18:
print(name, "is eligible for a
driving license.")
else
print (name, "is not eligible for a
driving license. ")
Sample run:
Enter name Ria
Enter age: 18
Ria is eligible for a driving 1icense.
OF CONTRO
FLOW
9:
323
itea function print the table of given number. The number has
a
Sample Run
the user.
entered by
to be Enter number :3
Ans. 3x 1 = 3
n int(input("Enter number:")) 3x2 6
11):
for i in range (1, 3 x 3 = 9
print(n, "x", i , "=", (n * i ) )
3x 4 12
3 x 5 15
3 x 6 118
3 x 7 21
3 x 8 24
3x 9 27
3 x 10 30
4. Write a program that prints n1iininium and maximum
of frve numbers entered by the user.
Ans.
n int(input("Enter a number:")) #1st number read
mn, mx = n, n

for i in range (4): #next 4 numbers being read


n
int(input ( "Enter a number: "))
if mx < n: Sample Run
mx =
Enter a number :5
if mn > n
Enter a number :3
mn = n
Enter a number :7
print("Maximum of numbers entered ", mx) Enter a number :2
print("Minimum of numbers entered: ", mn) Enter a number :1
Maximum of numbers entered : 7
Minimum of numbers entered : 1
Write aProgram
prog to check if the year entered by the user is a leap
year or not.
Ans.

if
int(input (" Enter a 4-digit year :))
yr %100 ==
0: # century year check
if yr %
400 ==

leap True
else
leap =False
elif yr
%4 ==

leap True
else Sample Run

If
leap False Enter a 4-digit year :1900
leap True
==
1900 is not a leap year
elseprint(yr, "is a
leap year") Enter a 4-digit year :2000
prnt(yr, "is not a leap year 2000 is a leap year

Enter a 4-digit year :2016

2016 is a leap year


324 COMPUTER ENCE WITH
PYTHON
10, 15, 20, 25, upto n 7ohere n11 an intos.
isis an
5. Write a program fo generate the sequence:-5,
-

integer input by
-
. .

the user.
Ans. Sample Run
n int(input("Enter limit "))
sign =-1 Enter 1imit : 38
for i in range( 5, n, 5): -5 10 -15 20 -25
term = i * sign
30-35
sign sign *-1
print(term, end = " ")

6. Write a program to find the sum of1+1/8+1/27..1/n', ohere n is the number input by the user

Ans.
n int(input("Enter limit (n):"))
SSum
print("1", end = " ")
# first term printed
Ssum +1 # first term added
for i in range(2, (n +1)): # 2nd term onwards
icube = (i *i *i)
term 1/ icube
ssum+ term
print("+ 1 / " , icube, end = " ")

print("=", SSum)

Sample Run

Enter 1imit (n): 5


1+1/8+1/ 27 1/ 64 1/ 125 1.185662037037037

7. Write a
program to find the sum of digits of an integer number, input by the user
Ans.
num int(input("Enter number "))
Ssum = 0 Sample Run
nnum= num
Enter number 23903
while (nnum != 0): is:
Sum of digits of number 23903
digit nnum % 10
nnum nnum // 10
ssum += digit

print("Sum of digits of number", num, "is : ", ssum)


8. Write a function that checks whether
an
input number is a palindrome or not.
INote. A number or a string is called
palindrome if it appears same when written in reverse o
example, 12321 is a palindrome while 123421 is not a palindrome]
Ans.

num
int (input ("Enter number "))
rev 0
nnum = num
OF CONTROL
Chopler
9:
FLOW 325
= 0):
while (nnum Sample Run
digit nnum % 10;
nnum
nnum // 10 Enter number: 34543
rev
*
10 + digit 34543 is a palindrome number.
rev =SSSSSSSE=SEESSSE=:
== num:
i f rev Enter number : 6787
print(num, "1s a palindrome number., ")
6787 is not a palindrome number.
else
print (num, "is not a palindrome number.")

9. Write a program to print the following patterns:


*
1
** *
2 1 2
3 2 12 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5

(ii) 12 3 45 (io)
*
1234
*
123
12

Ans. () (i)
n 5 # number of lines
n 5 # number of lines
s n* 2 1 # for initial spaces
#upper half
k= round(n/2) * 2 # for initial spaces for i in range(1, n+1):
for i in range (0, n, 2):
for j in range(0, s):
print(end =" ")
for j in range(@, k+ 1):
for j in range(i, 0, -1):
print(end=" ") print(j, end=" ")
for j in range (@, i + 1):
for j in range(2, i+1)
print("*", end ="") print(j, end =" ")
k k - 2
S S -2
print() print()
#lower hal1f
k 1
for i in
range(n-1, 0, -2):
Sample Run
for j in range( , k+2):
p r i n t(end = " ")

tor 1
j in range(®, i-1):
212
print("*", end="") 3 2 1 2 3
k =k+2 4 3 2 1 2 3 4
print() 5 4 3 2 12 34 5
Sample Run
*

**** *

R
COMPUTER SCIENCE WITH DVT
326 PYTHON -H
(io)
n
n 5 # number of lines j n-1
# for initial spaces
print(' '*(n)+'**")
for i in range(n, e, -1): for i in range(1, 2*n):
for j in range( 1, S+1 ):
print(end = " ")
ifi n:

in range(1, i +1):
print( *(d-n)+"**+" '"(2*j-1)4'
for j print(j, end = " ") j-=1
else
S+ 2
print(''*(n-i) +**'+' "*(2*1-1) 4
print()
if n>1:
print(' '*n+'*')
Sample Run
Sample Run
1 2 3 4 5
1 2 3
12 3
1 2
1

10. Write a program to find the grade of a student when grades are allocated as given in the table belozw.

Percentage of Marks Grade


Above 90%

80% to 90% B

70% to 80%

60% to 70% D
Below 60% E

Percentage of the marks obtained by the student is input to the program.


Ans.
marks float (input("Enter marks: "))
if marks = 90
8rade "'A'
elifmarks >= 80
grade 'B Sample Run
elif marks >= 70 :
Enter marks : 90
grade = "C is A
For marks 90.0 the Grade
elifmarks = 60
S+SESSSEEE5S5-
grade = 'D'
Enter marks 80
else For marks 80.0 the Grade 15
B

grade 1E
print("For marks", marks, "the Grade is", Enter marks : 69.9
grade) Grade 1s
For marks 69.9 the
p:
FLOW
OF
CONTROL
327
CASE STUDY-BASED QUESTIONS

1l driven program tihat has options to accept the mnarks of the student in five major subjects in
Vrite a menu

61 and display
the same.
Class X
ulate the
sum
ofthe marks of all subjects.
Divide the total marks by number of subjects (i.e., 5), calculate
percentage =total marks/5 and display the percentage.
the criteria
Cind the grade of the stuaent as per following
Criteria Grade
percentage > 85 A
percentage < 85 && percentage 7 5 B
percentage < 75 && percentage = 50 C
percentage < 30 && percentage > 50 D
percentage < 30
Reappear
Let's peer review the case studies of others based on the parameters given under "DOCUMENTATION
TIPS" at the end of Chapter 5 and provide a feedback to them.
Ans.
"getting marks in 5 subjects, calculating total percentage and grade""
total 0
for i in
range(5)
narks float(input ("Enter marks in subject "+ str(i + 1) +" : "))
total+= marks
perc total/5
if perc = 85
8rade 'A'
elifperc = 75
grade 'B'
elif perc = 50
8rade 'C
elif perc = 30
8rade 'D'
else Sample Run

grade "Reappear Enter marks in subject 1 : 67


otal marks", total, "\t Percentage :", perc) Enter marks in subject 2 : 56
Pnt ("\t\t\t Grade:", Enter marks in subject 3: 48
grade) marks in subject 4 : 67
Enter
5: 54
Enter marks in subject
Total marks: 292.0 Percentage: 58.4
GradeC

Enter marks in subject 1 : 89

Enter marks in subject 2: 92


Enter marks in subject 3 : 93

Enter marks in subject 4 92


Enter marks in subject 5 : 90
Percentage : 91.2
Total marks : 456.0
Grade A
328 COMPUTER SCIENCE
WITH PYTHO

GLOSS ARY
Block A group of consecutive statements having same indentation level.

Body The block of statements in a compound statement that follows the header.
Empty statement A statement that appears in the code but does nothing.
Infinite Loop A loop that never ends. Endless loop
Iteration Statement Statement that allows a set of instructions to be pertormed repeatedly.
Jump Statement Statement that unconditionally transfers program control within a function.
Looping Statement Iteration statement. Also called a loop.
Nesting Same program-construct within another of same type of construct.
Nested Loop A loop that contains another loop inside its body.
Suite Block.

Assignments
For
Solutions for
Type A Short Answer Selected Questions
Questions/Conceptual Questions
1. What is the common structure of Python compound statements ?
2 What is the importance of the three
3. What is
programming constructs
empty statement ? What is its need ? Scan
4. Which Python statement can be termed as
empty statement ?
QR Code
5. What is an
algorithm ?
6.
What is flowchart ? How is it useful?
a

7. Draw flowchart for


displaying first 10 odd numbers.
8. What is
entry-controlled ? loop
9. What the four elements of a while
are

10. What is the difference


loop in Python?
between else clause of if-else and else clause of
11. In which cases, the else clause of Python loops?
12.
a
loop does not get executed?
What are jump statements ? Name them.
13. How and whern are named conditions useful?
14. What are endless loops ?
Why do such loops occur ?
15. How is break statement different
from continue ?
Type B Application Based Guestions
1. Rewrite the following code
fragment that saves on the number of
if (a
== ) : comparisons
print ("Zero")
if (a 1)
==

print ("one")
if (a - 2 ) :
print ("Two")
if (a == 3)
print ("Three")
CONTRO
o p e r :F L O W O F
OF
:
FLOW
329
conditions will this code fragment 7. What is following code
Under what

print "water" ?
doing ? What would it
print for input as 3?
iftemp 3 2 n int (input( "Enter an
integer: " ))
rint ("ice")
e l i ftemp < 2 1 2 :
ifn<1
print ("invalid value")
print ("water") else
for i in range(1,
else:

print ("steam")
n +1):
print (i * i)

produced by the followin


isthe.output
8. How are following two code
What
from one another ? Also,
fragments different
code?
predict the output of
the following code
X 1 fragments:
i fx 3
i fx 4 : (a) n int(input( "Enter an integer:")
print ("A", end = ' ')
if n> 0:
else
for a in range(1, n +n):
print ("B", end = "' ') print (a / (n/2))
else
elifx 2:
print ("Now quiting")
if (x I= 0):
print ("C", end = ' ')
) n = int (input( "Enter an integer: "))

print ("D") ifn>0


for a in range(1, n + n) :
What is the error in following code? Correct the print (a / (n/2))
Code:
else
weather 'raining' print ("Now quiting")
if weather = 'sunny:
9. Rewrite the following code fragments using for
print ("wear sunblock")
elif weather = "snow": loop
print ("going skiing") (a) i 100
else: while (i>0)
print (weather) print (i)
Mhat s the output of the following lines of code ? i= 3
while num > 0 :
if int('zero') == 0 (6)
print (num % 10)
print ("zero") num num/10
elif str(@) 'zero ==
)while num > 0:
print (0) count += 1
elif str(@) == '0': Sum += num
print (str(®)) num 2
else: 10
i f count
==

print ("none of the above") print (sum/float(count))


Find
below and break
COrrecterrors
in the code given
the code following code fragments using
while loops :
10. Rewrite
if n == 0 min = 0
print ("zero") (a)
max num

elifn== 1
print ("one")
if num <
min = num
0:

elif max = e # compute sum


of integers

n 2: # from min to max

print ("two") for i in range(min,


max + 1):
else n 3: ==
sum + i
print ("three")
330 COMPUTER SCIENCE WITH PYTHON
-X
(b) for i in range(1, 16) : ()for i in range(4)
if i% 3 == 0 for j in range(5):
print (i) if i +1 ==
j or j +i == 4:
print ("+", end = '')
else
print ("o", end = ' ')

print()
11. Predict the output of the following code fragments:
(a) count = 0 6 ) x= 10
while count < 10:
print ("Hello") while X > y:
count += 1 print (x, y)
X = X .
1
y = y+ 1

(c) keepgoing = True (d) x = 45


(e)forxin[1,2,3,4,5]:
100 whilex < 50 print (x)
while keepgoing print (x)
print (x)
x = X 10
ifx < 50
keepgoing = Falsee

) for x in range(5): g forp in range(1, 10): (h) forq in range(100, 50, -10)
print (x)) print (p) print (9)

for z in range(-500, 500, 100): ) fory in range(500, 100, 100):


print (z) p r i n t (" * ", y)

(k) x = 10
() forxin [1,2,3
y 5 for y in [4, 5, 6]:
for i in range(x-y * 2):
print (x, y)
print (" % ", i)

(m) for x in range(3): (n) c=0


for y in range(4) : for x in range(10):
print (x, y, x + y) for y in range(5):
+ 1
print (c)
12. What is the output of the following code ?
for i in range(4):
for j in range(5):
if i+1 ==
j or j +i == 4
print ("+", end = '')
else:
print ("o", end = ' ')

print()
?
13. In the nested for loop code above (Q. 12), how many times is the condition of the if clauseevaiua
w OF CONTROL
OF Co
F L O W

oer
9: 331
hon
the following Python programs implement
Which o fthe the control flow
graph shown ?

True

true

n int(input(..)

false false
print ('whatf'), nA2
n= A1
ue
continue

true

break

print ("'ever)

() while True (6)while True


n
int(input("Enter an int: ")) n int(input("Enter an int: "))
ifn = A1 if n ==A1
continue continue
elif n == A2 elif n == A2
break break
else else
print ("what") print ("what")
else: print ("ever")
print ("ever")

)while True:
n=int(input ("Enter an int: "))
ifn == A1
continue
elif n
== A2
break
print ("what")
print ("ever")
5. Find
error. Consider the following program:
a
int(in
while a
1nput("Enter a value: "))
l= 0:
COunt count +1
a
t(input ("Enter value: "))
print("You ente
uentered", count, "values. ")
a
332 COMPUTER SCIENCE WITH
PYTHON -
It is supposed to count the number of values entered by the user until the user enters
nters 0 and
and #h
then
the count (not including the 0). However, when the program is run, it crashes with
message after the first input value is read
the foll
the following diserror
play
Enter a value: 14
Traceback (most recent call last):
File "count.py", line 4, in <module>
Count COunt + 1
NameError: name 'count' is not defined

What change should be made to this


program so that it will run correctly ? Write the modification
needed into the program above, that is
crossing out any code that should be removed and clearly indicatino
where any new code should be inserted.

Type C: Programming Practice/Knowledge based Questions


1. Write Python script that asks the user to enter a length in centimetres. If the
a
user enters
a negative
length, the program should tell the user that the entry is invalid. Otherwise, the
the program should convert
length to inches and print out the result. There are 2.54 centimetres in an inch.
2. A store charges { 120
per item if you buy less than 10 items. If you buy between 10 and 99 items, the cost
is7 100 per item. If you
buy 100 or more items, the cost is 70 per item. Write a
program that asksthe
userhow many items they are
buying and prints the total cost.
3. Write a
program that reads from user (i) an hour between 1 to 12 and-

(ii) number of hours ahead. The


program should then print the time after those many hours,
eg,
Enter hour between 1-12 : 9
How many hours ahead : 4
Time at that time
would be : 18clock
4. Write a program that asks the user for two
numbers and prints Close if the numbers are within .00l or
each other and Not close otherwise.
5. A year is a
leap year if it is divisible by 4, except that years divisible
they are also divisible by 400. Write a program by 100
that asks the user for a year andare
prints leapwhethert
not out years unies
iD*
leap year or not.
6. Write a to
program input length of three sides of a triangle. Then check if these sides will form a triange
or not.

(Rule is :a+b> c;b+c> a;c+a> b)


7. Write a short program to
input a digit and print it in words.
8. Write a short program to check whether
square root of a number is prime or not.
9. Write a short program to
print first n odd numbers in
10. Write a short program to descending order.
print the following series
() 1 4 7 10. . . 40.
(ii) 1 -4 7 10. 40
11. Writeshort program to find
a
average of list of numbers entered
12. Write a to
program input 3 sides of a triangle and through keyboard.
triangle. print whether it is an
equilateral, scalene o
13. Write a
program to take vith 4
"ends with 4", if it ends with 8,
an
integer a
input and check whether it ends with 4 or 8. t
as an
print print "ends with 8", otherwise print "ends withIr
14. Write program to take N (N>
a
20) as an input from the user. Print numbers from 1l
ne When
the

number is multiple of 3, print "Tipsy", when it is a


a to multiple
of both, print "TipsyTopsy". multiple of 7, print "Topsy". VWhen it
FLOW OF CONTROL 333
Cioer
prog.
ogram to find largest number of a list of numbers entered through keyboard.
short
input N;numbers and then print the second largest number.
a
Write to
program

Write a integers,
e
write a program to find those which are palindromes. For example, the number
a list of it
it reads the same from left to right and from right to left.
p a l i n d r o m e
as
Given
a
4921234is to do the
mplete Python
program following
a
Write

an integer X.
read
(9 the.number of digits n in X.
determine

Y that has the number of digits n at ten's place and the most significant digit of X
integer Y
orm an
(ii)
at one's place.
(ino) Output Y.
ample, if
if XX is equal to 2134, then Y should be 42 as there are 4 digits and the most significant
(Forexample,
number is 2).
e a Prthon program to print every integer between 1 andn divisible by m. Also report whether the
divisible by m is even or odd.
number that is
Write Python programs to sum
the given sequences

.print 7 terms) (b) 12 +32 +5 + n (Input n)


13 17
21. Write a Python program to sum the sequence

12 (Input n)
n!
.Write a program to accept the age of n employees and count the number of persons in the following age
group: () 26 35 (it) 36 4 5 (ii) 46 555.

&Wrte programs to find the sum of the following series :

0- nput x) (6) x+ (Input x and n both)

4.
Write programs to print the following shapes
(b) (c) (d)

*
*** *
*
*
*
*
5. White
gams using nested loops to produce the following patterns
A
A B (b)A
B
B C
A B
CC C
C D D D DD
A BCD
B C E E E E E E
DE F

(d) 2
4 4 4
4 4
6 6 6 66 6
6
88 8
8 8 8
334 COMPUTER SCIENCE WITH
PYTu
26. Write a program using nested loops to produce a rectangle of "s with 6 rows THON -N
27. Given three numbers A, B and C, Write a program to write their values in
IS and 20 *s
in an e per
example, if A =12, B=10, and C =15, your program should print out:
Smallest number = 10
an
ascending orderow.
Next higher number 12
Highest number = 15

28. Write a Python script to input temperature. Then ask them what
units, Celsius or E.
temperature is in. Your program should convert the temperature to the
other, unit.
F 9/5C +32 and C 5/9 (F 32). =
The co et,the
ons are
29. Ask the user to enter in Celsius. The
a
temperature program should print a message has
temperature: based on the
AIf the temperature is less than -273.15, print that the
absolute zero. temperature is invalid because it is L.
oelow
I f it is exactly -
273.15, print that the temperature is absolute 0.
I f the temperature is between -273.15 and
0, print that the temperature is below
I f it is 0, print that the freezing
temperature is at the freezing point.
I f it is between 0 and 100,
print that the temperature is in the normal range.
I f it is 100, print that the
temperature is at the boiling point.
A If it is above 100,
print that the temperature is above the boiling point.
30. Write a program to
display all of the integers from 1 up to and including some
user followed
by a list of each number's integer entered by the
prime factors. Numbers greater than 1 that
only have a single
prime factor will be marked as primne.
For example, if the user enters 10 then the output of the
program should be
Enter the maximum value to
display: 10
1 1
2 2 (prime)
3 3 (prime)
4 2x2
5 5 (prime)
6 2x3
7 7 (prime)
8 2x2x2
9 3x3
10 = 2x5
CHAPTER 9: FLOw OF CONTROL
Multiple Choice Questions
1. (a) 2. (b) 3. (c) 4. (a) 5. (b) 6. (a), (6)
7. (), (d) 8. (b) 9. ) 10. (b), (c) 11. (d) 12. (c)
13. (c) 14. (b) 15. (d) 16. (d) 17. (d) 18. (d)

(ii)
19. (c), (d) 20. (b) 21. (c) 22. (b), ( 23. (a) 24. (a)
25. (a) 26. () 27. (6) 28. (b) 29. (c) 30. (c)
31. (a), (b) 32. (C), (d) 33 (b) 34. (a), (c), (d) 35. (b), (d) 36. (c)
37. (b) 38. (e) 39. () 40. («), (e) 41. (e) 42. ()
43. (b), (c)

Fill in the Blanks


1. if 2. passS 3. for, while 4. sequence, selection/decision, repetition/iteration
5. indentation 6. if-else 7. in 8. in, non in 9. loop 10. for
11. while 12. else 13. else 14. break 15. break 16. continue
17. jumpP 18. inner

True/False Questions
1. T 2. T 3. F 4. T 5. F 6. F
7. T 8. F 9. T 10. F 11. F 12. T
13. F 14. F 15. T

You might also like