Chapter-9 - Flow of Control
Chapter-9 - Flow of Control
Flow of
Control
In Tis Chapter
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.
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.
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
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==' '
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
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 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:
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]
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
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
sum2 + 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 ==
==<<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 =" ")
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:
9:
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
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===
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
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 :
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.
*/%
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
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)
[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)
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
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
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:
rogram
import math
elifdelta ==0:
root1 = - b / (2 * a ) ;
SSS:SSSSSSSSS:
Enter a : 2
Enter b : 3
Enter c : 4
KOots are cOMPLEX and IMAGINARY
==== RESTART ==*
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.
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
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.
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 2
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:
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
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
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)
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
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
ifstring in line:.
print (string, "is part of", 1ine.)
else
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.
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
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
prinis
printfa a)) are printed.
Pris
4
16.
7
49
CONTROL
o p r
9:
e r 9 .
FLOW OF 291
(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:
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
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)
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
n 1 T h e l o g i litional expression
c a l l c o n d i t i
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
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
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
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
Enter a nutber: 4
Thefactorial of 4 is 24
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.
if <condition> i f <condition>
Statements 4 is the break break
first statement after statement 2 statement 2
statement 3
t e
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
termination the break statement or the test-condition's result. Recall the last part of above
program, i.e.,
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.
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.
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
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)
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
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
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
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 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
Now consider the same loop as above but with a break statement:
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.
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
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:
count count+1
ans input( "Want to enter more numbers? (y/n)..")
else loop-else suite
print ("You entered" count, "numbers so far .")|
,
else:
The above code will print the result of execution of while loop's else clause, i.e..
Consider another loop - this time a for loop with empty sequence.
* *
* *
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 :
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
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.
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.
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
Python
The if.else statement tests an expression and depending upon its truth value one ofthe two sets-of-action is executed,
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.
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
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 =
"
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
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
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)
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!" " ")
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
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)
(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: " , \
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: "))
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
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 = ' ')
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
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
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
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
# 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
print(a) print(i)
a- 2 (in) country = 'INDIA
Sum= Sum + ii
i i+2
print(sum)
COMPUTER SCIENCE WITH
PYTHON-
322
in range(1, 4)
:
(v) for x
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
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
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
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
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
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.")
(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.
80% to 90% B
70% to 80%
60% to 70% D
Below 60% E
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
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
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)
elifn== 1
print ("one")
if num <
min = num
0:
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
) for x in range(5): g forp in range(1, 10): (h) forq in range(100, 50, -10)
print (x)) print (p) print (9)
(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)
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:
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
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
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.
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)
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