50%(2)50% found this document useful (2 votes) 2K views31 pagesPreeri Arora Chapter5 First Year
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Condit
ional and
Looping Constructs
5.1 INTRODUCTION
In the previous chapters, we have learnt the
bas of Python programming where we
dealt with simple short programs containing a
sequence of instructions given for carrying out a
particular task. They were all in a sequence, i.e,
one after the other. In real life too, this sequence
of operations is observed when a school bus
carries school children from school to home and
vice versa (See Fig. 5.1).
‘There is only one way and the driver has no choice
but to follow the road from one bus stop to
another and reach home/school by following a
sequence.
Fig. 5.1: Flow/Sequence in Real World
Similarly, Python also executes one statement after another in a program, All these statements
are executed by the CPU. The CPU, as you know, has three parts—Arithmetic Logic Unit (ALU),
Control Unit (CU) and Memory Unit (MU).
Central Processing Unit
Control Unit
Output
Input
Device
Device
Arithmetic Logic Unit
The Arithmetic Logic Unit involves
all mathematical operations and
conversions. We will now focus on the
Logic Unit which makes a computer
think; so we need to write the code,
In real-life scenarios also, we often go
with the flow and tend to take decisions,
such as after 10th standard, we decide
which stream to go for and after
completing graduation/post-graduation,
one has to decide which company to join.
Similarly, if you have ever used Google
Maps direction services to reach from
‘one place to another, you might have™
imes i path: the least crowded path, shortest g,
noticed that sometimes it shows more than one p: : ed Path, Shortest diay,
th, etc, and you can decide which path to take. A decision may i sing one
path, etc., 7 *
two or more possible options.
If itis raining, | will use an umbrella so that I don’t get wet (Fig. 5.2). This is a type of bra,
If one condition is true, that is, if itis raining, | will take my umbrella. If the condition ig
but false, then I will not take my umbrella.
chin,
Rot true
IFit is raining, \
Take an
umbrella
Sol moat
Fig. 5.2: Decision-making
Similarly, in Python also, we have a keyword ‘if’ which helps in taking decisions. In the above
figure, we have used a tool for depicting this decision-making which is a flow chart,
Before we move on to the concept of program control statements, which are the Python
constructs used to perform repetitive actions and for making decisions, we will discuss the typ:
of statements available in Python.
5.2 TYPES OF STATEMENTS IN PYTHON
Statements are the instructions written in the source code given to the computer for executing
any task. These help the user to obtain the desired output by working and manipulating date,
making decisions and repeating the set of instructions. Statements constitute the smallest
executable unit within a Python program. Python statements are classified into three types:
1. Empty Statement
2. Simple Statement (Single Statement)
3. Compound Statement
1. Empty Statement: It is the simplest statement or, more precisely, we can say it is an emp?
statement which serves as a placeholder in Python. pass is a special (empty) statement ®
Python that does nothing. It only works as a dummy statement.
Its syntax is:
pass
08
Itcan be used when a statement is required syntactically but the program requires nO
to be performed, Since Python does not support empty code blocks, we can use pass sta‘®
for the no-operation in the if-condition block, if-else block and even in while loop.
a --
|g, simple Statement (Single Statement); A simple statement in Python comprises a single
| ogical statement. For example, consider the following single statement:
55> name=input ("Enter your Nam:
>>> print (name)
assignment statements are simple statements like:
4 por x= 10
which means that we are assigning a value “10” to the variable "x". This we call a simple
statement.
| The computation statements (expression statements) are also called simple statements.
‘These statements will compute or calculate some expressions and return the results.
For example,
poo x=10 +15
is an expression statement.
‘Thus, a simple statement is described as a single executable statement in Python.
3, Compound Statement: A compound statement is a statement which comprises @ BrouP of
statements. The compound statements usually execute when a condition is satisfied, or &
code block is called directly or through a function call
Compound statements are spread into multiple logical lines or several single statements but
aligned together into a single unit. Its syntax is:
Here, the header line starts with the keyword and ends at colon (:).
The body consists of more than one simple Python statement or compound statement.
5.3 PROGRAM CONTROL AND FLOW
The control and flow of a program in any programming language can be broadly classified into
three categories:
1. Sequential Statements
2. Selection Conditional Statements
3. Iterative or Looping Statements
Ina Python program, statements can be executed sequentially, selectively or iteratively. Now, we
shall discuss these program control flow constructs in brief.
1. Sequential Statements: Sequential statements in the Progr
are executed in a sequential order or in a linear fashion, On
after another, without any jump in the program, In Fig. 5.3,
Statement 1 will be executed first, followed by Statement 2
and then Statement 3. This represents the default flow of
statement and is the simplest one-
Fig. 5.3: Sequential Statements
a2, Selection/Conditional Statements: Selection/Conditional
~ St tements in a program are executed when the program uses
acondition to decide which set of statements is to be executed
between two or more alternative sets of. tee
Ih conditional statements ‘if.else’ statement is used.
InFig, 54, ‘body of statement’ will be executed iftest condition
evaluates to true otherwise ‘body of else’ will be executed.
These are also called Decision Constructs.
3, Iterative or Looping Statements: Iterative or Looping
statements in a program are executed when a certain set of
statements needs to be executed multiple times in a loop.
Iterative statements constitute for and while loops. In Fig. 5.5,
body of loop will be executed until test expression evaluates
to true.
The set of statements that is repeated again and again constitutes
the body of the loop and this process is termed as iteration.
The condition on which the execution or exit of the loop
depends is called the exit or test condition.
5.4 USE OF INDENTATION
In simple terms, indentation refers to adding white space before a statement. Indentation is a
very important concept of Python because without proper indenting the Python code, you will
end up seeing IndentationError and the code will not get compiled.
Fig. 5.5: Iterative Statements
In most programming languages, the statements within a block are put inside curly brackets
However, Python uses indentation for block as well as for nested block structures. (Fig. 5.6)
Leading whitespace (spaces and tabs) at the beginning of a statement is called indentation. In
Python, the same level of indentation associates statements into a single block of code. The
interpreter checks indentation levels very strictly and throws up syntax errors if indentation is
not correct. It is common practice to use a single tab for each level of indentation.
How the interpreter
visualizes
Fig. 5.6: Indentation in Python
In the above example,
+ Statement (line 1), if condition (line 2) and statement (last line) belong to the same block
which means that after statement 1, if condition will be executed, and suppose the /
condition becomes False, then Python will jump to the last statement for execution.
«The nested if-else belongs to block 2 which means that if nested if becomes False, then Pyth"
will execute the statements inside the else condition.
=~
a
oar
+ Statements inside nested if-else belong to block 3 and only one nent will be executed
depending on the if-else condition,
thus, Python indentation is a way of telling a Python interpreter that the group of statements
pelongs to a particular block of code,
5.5 CONDITIONAL CONSTRUCTS/STATEMENTS
The order of execution of the statements in a program is known as flow of control, It is dependent
on the programming constructs used while writing the program, Decision-making or conditional
constructs/statements are used to control the flow of execution of a program depending upon the
condition.
> There are four types of conditional statements in Python:
1. if'statement
2. if-else statement
3. ifelif-else statement
4, Nested if-elif-else statement
5.5.1 if Statement
if statement is the easiest method for making a decision in Python. It simply states that if
something is true, Python should perform the steps that follow and do nothing in case the
condition evaluates to false. In programming, decision-making or selection can be achieved
through the conditional statement. The simplest form is the if statement.
Syntax:
Header
if condition:
statement The statements inside
an “if” are indented at
statement (s) same level
>t ition is true, then the indented statement gets
the condition is true, Fig. 5.7(a): Flow Chart for
executed if Statement
———— [Colon is must.
False
> ‘The indented statement implies that its execution Is dependent
on the header.
> ‘There is no limit on the number of statements th
* ‘if’ is a keyword, followed by a condition and ended with ‘colon’.
* We can use the condition with bracket () al:
indented (usually 4 spaces) inside the
. nts (Block of code) are in
7 daeme a Seca only if the condition evaluates to true, otherwise
7 eral ane the block of statements inside if statement and only statement 2
ntrol
will be executed.
at can appear under an if block.
\so but it is not mandatory.Giese
1a set of statements as a blOck that pyy
‘© Indentation is a process of declaring 2 sta
i i on
recognizes in the code. In other words, statements with the same indentation are considered yo 4)
a block or group. eit is sald to be a Com
ck, is sl our
«When a set of statements are indented under the same Do 1POUNE Statemen,
inde th
Mrbecin nth a neaer ending with 2 atone sign ana the statements ler the same indentation,
are marked as a block,
tement 0
Let us look at an example to understand if statement in Python.
Practical Implementation-1
Ilustrating the concept of if statement, to determine whether a person IS eligible to vote,
Tae at Tost Raps Wsen HO
ee erate if stavenent.
Python progran to illustrate if statens!
. astatenent]
ge, Sag ugzue center age of a person #')) $etatenent2
if age >= 18: e" fstatenent?
AOE Z(t 1s eLigibie to cast the vote”) Se
print ("ram Not in if")
for nore information.
Pype “copyrights, “eredite” oF "iicense()"
22> nameneeenwennene= RESTART! Cz\chapter S\PgTA3-PY
Enter age of a person :10
Tan Not in if
Explanation:
4. statement asks the user to input age.
2, statement2 Age >= 18 is the test expression.
3. The body of if, i
When variable ‘Age’ is equal to 10, ie, the inputted age is less than 16, the test expres)
becomes false and body of ifstatement is skipped, ie, statement3 does not get executed atall
_ statement3 is executed only when if condition evaluates to true.
5, statement4 falls outside of the if block (un-indented), Hence, it is executed regardless of the
test expression.
Practical Implementation-2
illustrating the concept of if statement, display the grade of the topper in the class.
(om toy- Chr Span dpy O65 8 TL TT
SSS a a a |
[grade = input ("enter grade of a
fe "grade == as: —
print. ("Well done!)
‘Fetatenentl
‘statement?
#statement3****Output of the programersess
+33f39¢0932b4, Mar 70 2010, 16
2 bit” Untel)) on wing?
‘opyright", “credits” or “1iconse()" for more info
"wo" RESTART: C:\chaptor 5\prgm_
Enter grade of a person:
Well done! Pe *
Now consider a situation when the user inputs grade other
than ‘X; then nothing shall be executed, and the flow control
of the program shall terminate on the condition evaluated as
false without notifying anything to the user.
Here, we need a second type of conditional if statement called
jf.else that provides an alternative execution. if..else allows
to have two possibilities and the condition determines which
branch gets executed.
Learning Tip: A statement
for statements (block of code)
indented (usually 4 spaces) inside
the if statement is executed only
if condition evaluates to true,
otherwise the control skips the
block of statements inside if and
control goes to the outside of the
if block (un-indented)..
Therefore, we will improvise the above programs for the false
situations by introducing the ‘else’ part in association with the if statement.
5.5.2 if-else Statement
‘if statement alone tells us that if a condition is true, it will execute a block of statements and
if the condition is false, it won't. But what if we want the program to display some appropriate
message or to execute certain set of instructions in case the condition becomes false. Here comes
the else statement. We can use the else statement with if statement to execute a block of code
when the condition is false as shown in Fig. 5.7(b).
condition:
statement (s) t
else:
statement(s)
False
Here: True
> ‘ip and ‘else’ are keywords. Cet) tebe)
> A statement or statements (Block of code)
indented (usually 4 spaces) inside the if
statement is executed only if condition
evaluates to true, otherwise statements Fig. 5.7(b): Flow Chart for if-else Statement
following else will be executed.
Let us consider an example that explains if-else construct along with its associated flow chart
and Python code.- 5
Example 1:
‘To develop a program that asks the user to input the number of working hours ang
per day. It then calculates how much money they earn in 2 week and display an app, ™ng
message based on their earnings. Pia
| Python code
Flow chart
ae
lypay = int (input (ag,
much do you earn per
hour?")) 7
hoursperweek =
input ("How many hourg
week do yoo *
work?"))
hourly pay
weekly pay =|
hours per week
weeklypay = hourlypay «
hoursperweek
output output if weeklypay > 400:
can afford ty ae print ("You can afforg
to live alone.»
Tive alone
Practical Implementation-3
Illustrating the concept of if-else
You can't afforg
to live alone.)
statement. (Modification of Practical Implementation-1),
} wee v. 1900 98 bit (Intell) on ving,
Syoe Heopyrignt", sereaiter oF "License ()* for more
Yetormitice
ioe eligible to vote
Let's take another example to gain a better understanding of if-else statement.
Practical Implementation-4
Write a code to find whether a given number is odd or even.
Print ("od
- a+eeee99*Oulput of the progra
Grr EEE ewes tome
oo ng So
ie093208, Har Y6rOTeAG) [HIE V.1900 3
nee
Prthon 3n6u5 (99.6
pte dately) on winde
ype tcopyeight™, “credits” or "Lick
pe
0" for more information.
RESTART: Ci\chapter 8\pgem_6,py ==emeneanamen
ical Implementation-5
pact
ae to find absolute value of a number in Python,
am to
post
or Tn Python
x = int (input "Enter the nun
Tee or
[print ("absolute value 42")x)
eset
print (%
I
RESTART: ¢:/Users/proet,
je_viue.py.
Enter the number: -50
absolute valve is 50
tute value is")
practical Implementation~6
program to check divisibility of a number.
JiProgran to check divisibility of a number
[print Enter a Number (Nuserator): “>
fhuan = int (input?
[Prine (Enter a umber (denoainator):
‘bund = Ane Gnpot OD
| munndnundeso:
‘rine ("\n" saer(nuan)+ * 43 divisible by * +strtnunay
lerzes
Hint (*\n" ¢ste(nuan)¢ * {3 not divisible by * +str¢nuna))
RESTART: Ct/ls0x9/preeti/APPOA
oY Enter a munber (cencminator):
Exfer a umber (nerator): fe
3
Enter a wunber (denoainator):
a
aivisinie by ¢
{120 12 not ctvisible by 33__}
me atime, there are situations that require multiple conditions to be checked and, hence, may
ad to many alternatives. In such a case, we can chain the conditions using if..elif as discussed
'nthe upcoming section.
553 it-elit-else Statement
nee construct is used in the situations where a user
ndtiong. among multiple options. As soon as one of the
asoguts Controlling the “if” is true, then statements
leider g pont that ‘if are executed, and the rest of the
al egg pP2SSed. If none of the conditions is true, then the
“to gganatement will be executed, and control flows from
ba -
Learning Tip: ‘ifelifelse
statement’—Each condition is
checked in order. If the first is
false, the next is checked and
so on. If one of them is true, the
corresponding branch executes,
and the statement ends.Syntax:
if condition:
statement (3)
elif condition:
tatement (3) Test Yes.
pression 2
elif condition
statement (
ves
statement (s) a > [Satria 3}
Fisiay Fig. 5.7(c) Flow Chart for ielif-else Statemery
> else is optional
> Number of elif is dependent on the number of conditions
> I the first condition is false, the next is checked, and so on. If one of the conditions is tre,
the corresponding statement(s) executes, and the statement ends.
Practical Implementation-7
Illustrating the concept of if-elif-else statement, accept the percentage of a student and display
the grade accordingly.
Ua rerey cigs BES
(a
it & program to accept percentage of a student and display grade
perc = float (Input "enter percentage of a student : ")) # atatenenti
if pore > 851 4 condition:
pein (at)
Joust pore > 70 and pare 60 and perc <«701 4 conditions Ht
print ('c")
Jelit perc > 45 and pere >>
j= aauananuewunene RESTART! Ci\Chapter 51 T.py samme
enter percentage of a studont + 78 PESE S\PEgN T py
B
>>.Explanation:
1. statement accepts the percentage as the input from the user.
2, Bach condition is checked in order. As per the inputted value of 78 as the percentage,
condition is false but condition? is true and, hence, the corresponding code of condition2
be executed and control will not even check other conditions.
Another example explaining the if-elif-else construct is as follows:
practical Implementation-8
ilustrating the concept of if-elif-else statement, accept the salary as input from the user and
calculate the tax payable.
(Benin cacy pase ad9
ca hea
accept & caleaiace ta SE
slasye int unpat(encer Salary of a person 7)) statement
“TRB cSteet ty + condiviont
4 conitton?
+ conditions
15000 “rax 5200.0
Practical Implementation-9
Program to sort three inputted numbers and arrange them in ascending order.
ftiaelapet atte ttc oumer:
Fr neGnpe Cine feces tants
12 Belneer Concer Siehdaber
ested
ics
Sininnanensyt
indenter, 27
Wrest
(LBs
inaa,maeey, 4
fesse genet
|
| iP xenyt
| Tain mid, mame x, ¥ 3
eiser RESTART! C1/Users/preet/Appoata/ocal
Binymidymaxez, YX
ERSY tsrae numbers 67
Enter second monmert #
Enter thisa numbers 14
Inunpers' in aveending order = $26 67
~5.5.4 Nested if-elif-else Statement
‘The nested if..elif.else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions. We can have many levels of nesting inside i
else
statements.
‘Syntax Example
if condition: var = 100
statement (s) Af var < 200
if condition: print ("value is less than 200")
statement (s) if var == 150:
elif conditio: print ("Which is 150")
statement (s) elif var == 100:
els: print ("Which is 100")
statement (s) elif var == 50:
elif condition: print ("Which is 50")
statement (s) elif var < 50: 7
else: print ("value is less than 50")
statement (s) else:
print ("Could not find true countenance")
print ("Good bye!")
We can have an if..eli
computer programming.
Jse statement inside another if..else statement. This is called nesting in
‘Any number of these statements can be nested inside one another: Indentation is the only way
to figure out the level of nesting, This can get confusing, so it must be avoided as far as possible,
Practical Implementation-10
Mlustrating the concept of nested if-else statement, find whether an inputted number is a 0 (zero),
a positive number or a negative number.
(Bimeniar Comme serie (elem
|[F Ge For_fan_ Opies vind Tab
fnum = float (input ("Enter a nunber: “)) #statenenti
if mun >=
Sf nun == 0;
Brint ("Zero")
else:
print ("Positive nunber")
else:
print ("Negative nunber")
Tae Top Op_vndn_Fa
Python 3.6.5 (v3.6.5:£59¢0932b4, Mar 20 2016, 1
2ibit (Iatel)] of win32
[Fuge “copyright, “credite® or "License ()" for nore information.
srecrerromeonenename RESTART: Ct\chapter 5\prgn_9.py semeneeenenene
fenter a number: §
Positive number: s the user to input a number,
sta is
sectearthe number is positive or negative o
che
Jate message.
ero and display an approy
we have learnt how to make a deci
sil 1 performing useful work, The progr
ee just one time and then stoppe
et
ion. ‘To take one path or another
mis we have worked upon till now have performed
ies of stePS «l. However, the real world doesn’t work this way.
ase the tasks that humans perform are repetitious. For example, the doctor might state that
att fed to exercise more and tell you to do 100 push-ups each day. If you just do one push-up,
so Malt get much benefit from the exercise and you definitely won't be following the doctor's
yor of course, because you know precisely how many push-ups to do, you can perform the task
jc number of times. Python allows the same sort of repetition using Iteration/Looping
hich we will discuss now,
ord
2 spel
decoments WI
enu-Driven/User’s Choice Program
Menu-driven program is a program that gets input from a user by showing the option:
known as the menu, from which the user chooses an option. Systems processing menu-d
programs are ordinary, starting from washing machines controlled by microprocessors to
Automated Teller Machines (ATMs). Take the case of ATMs; the user presses a single key
to indicate the type of transaction (if the user wants a receipt with cash or if an account
statement is needed). Also, the user presses a single key to indicate the amount of cash to
be withdrawn.
More often, when you visit a restaurant, the waiter shows you a list of items that can be
ordered. The list of items, out of which you select some items and place your order, is
termed as menu.
Like the menu, we can also design a program in Python that will allow a user to perform a
specific operation out of a given number of operations. Such a program is termed as menu-
driven program or user's choice program. Menu-driven program can be designed either
using multiple if statements or if-elif-else statement.
Method 1: Method 2:
Using multiple if statements Using if-elif-else statements
if choice == 1: if choice 1:
block 1 block 1
if choice elif choice
block 2 block 2
if choice else:
block 3 block 3
The above multiple choice construct allows you to select an option out of a number of choices,
When a condition for the given choice evaluates to True, the respective block of statements
will be executed,Practical Implementation-11
Write a menu-driven program to display a menu for calculating
acircle,
&
print ("1.2rea of circle")
print (*2.circuaforence of circle")
fensint (input ("enter your choice: "))
ie chal?
‘reint (input ("Enter radius of circle: "))
areal=(3.14%r*r)
print ("area of cizcle-",areal)
lenis enema:
Reint (input ("enter radius of circle:
cireun= 2*3.149R
qeqbtint(elzciaterence of clzcte =*,clreum)
print("snter the appropriate choice")
”
eg 1
RESTART: ¢:/Users/preoti/appData/!
jven-areacireun. py
Iarea of circle |
j2:cireunference of circle
Jzater your choice: 1 |
inter radius of circle: 25 |
Jarea of circle= 1962.5
|
RESTART: ct /Users/preeti/AppData/!
Wares of circle
2.Gineunterence of circle
Eater your choice: 2
fencer Fadius of cizel
[cizeunterence of circle = |
5.6 ITERATION
In our day-to-day life, we repeat tasks. For example, we repeat
paying electricity bill every month or, as shown in Fig. 5.8, a
silkworm lays eggs, turns into a caterpillar, becomes a pupa,
matures as a silk moth and lays eggs again and the cycle starts
again,
This kind of repetition is also called iteration. Repetition of a
set of statements in a program is made possible using looping
constructs.
To understand further, let us look at the following Python
program that prints the first five natural numbers:
print (1)
print (2)
print (3)
print (4)
print (5)
Bes meiner esse =
Fax (at fort fer Qyeome Wor 0
[fmonu-driven progran to display a menu for calculating |
tthe area of a circle and circunference of a circle
~
the area and circu
Meron,
8 op
Fig. 5.8: Life Cycle of a Silkworm
(Iterative Process)‘output:
What would you do if you were asked to print the first 100,000 natural numbers? Writing
1,00,000 print statements would not be an efficient solution. It would be tedious and not the
right way to do. Writing a program having a loop is a better solution here. The pseudocode is
given below:
1, Take a variable count and set its value to 1.
2, Print the value of count,
3, Check the condition (count<=100000)
4, Increment the variable (count += 1).
5, Repeat the steps 2 to 4 as long as count has a value equal to 100000.
Looping constructs provide the facility to execute a set of
statements in a program repetitively, based on a condition,
‘The statements in a loop are executed again and again as long as
a particular logical condition remains true. This condition
is checked through a variable called control variable. When
the condition becomes false, the loop terminates. It is the
responsibility of the programmer to ensure that this condition
eventually does become false, i.e,, there is an exit condition
and the loop does not continue endlessly.
Conditional Code
Ifthe condition
~is True
It the condition
Is False
For example, if we didn’t set the condition count<=:
the program would have never stopped.
00000 Fig. 5.9: Flow Chart for a Loop
> Aloop statement allows us to execute a statement or a group of statements multiple times.
The given diagram (Fig. 5.9) illustrates a loop statement.
‘Types of loops
Python programming language provides the following types of loops to handle looping
requirements.
1. for loop
2. while loop
‘while’ loops are also called ‘indefinite loops’ because statements are executed until a logical
condition remains true. ‘for’ loops are called ‘definite loops’ because statements are executed
for a definite number of times.5.6.1 for Loop
The for loop statement is used to iterate/repeat itself
over a range of values or a sequence. The for loop is
executed for each of these items in the range. These
values cai be either numeric of, as we shall see in
successive chapters, elements of a data structure like
a string, list, or tuple,
Initialization
Test
vession
With every iteration of the loop, the control variable
checks whether each of the values in the range has
been traversed or not. When all the items in the range
are exhausted, the body of the loop is not executed
anymore; the control is then transferred to the
statement immediately following the for loop.
In for loop, it is known beforehand how many times
the loop is going to be executed as depicted in the
flow chart given in Fig. 5.10.
Fig. 5.10: Flow Chart Depicting a fo,
Loop
Syntax of for Loop:
for in :
else: # optional
Her
> sequence may be a list, string or tuple.
> ‘else’ statement will be executed after all the iterations of for loop, if provided.
> Control_variable is a variable that takes a new value from the range each time loop is executed,
‘Example 1: Output:
for letter in 'PYTHON': P
print (letter) Y
T
5
°
N
‘Example 2: Output:
count = [10,20, 30, 40,50] 10
for ¢ in count: 20
print (c) 30
40
50
Example 3: Output:
numbers=(1,2,3, 4,5, 6, 7/8, 9,10] 2 is an Even Number
for n in numbers: 4 is an Even Number
ifne2 6 is an Even Number
print(n, ‘is an Even Number') |8 is an Even Number
10 is an Even Number
Note that the body of the loop is indented with respect to the for statement.
a~ :practical Implementation~12
iustrating the Concept of for loon statement,
Ssh ete
to fllustrate Tor Toop
Print (votcome,1,-tinos*)
*erers+Output of the programexssnnet
Eel)
2_Options Window Help
ae
ne
ftelcone 1 times vue
Explanatio
1, Heres loop control variable and will be assigned each value of a string 123% i
time i will be 1, then 2 and then 3,
2, Body of for loop will be executed for each value of loop variable i, i.e., 3 times.
In the first iteration, the loop shall get executed with i=1 and will print Welcome 1 time.
4. Then body of the loop will be executed with i=2 and will print Welcome 2 times.
Again the same method of execution shall take place with i=3 and will print Welcome 3 times.
, for the first
Practical Implementation-13
illustrating the concept of for loop statement.
1B pronseiec2oy- CorontGires.seecpy as) - © EEE
hee eint (‘coming out of the 2008")
RESTART: :/python36/pr0
Explanation:
In the given program, for loop is used to traverse through the string ‘GOA’ character and gets
printed on separate line. Once the for loop iterations get over, the else part gets executed and
finally the message “Coming out of the loop” gets printed.
1, The range function used in the above program will generate values as 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
h the ‘body of
2. ‘iis loop control variable and will be assigned each generated value, for wl
for loop’ will be executed.Practical Implementation-14
table of a number using for loop.
Program to generate the
esnesensQutput of the programs**"
:/chapter 5/pgrm_25.PY
Explanation:
1. The range function used in the above program will generate values as 1, 2, 3, 4, 5,6, 7,8,9, 19
2. ‘iis loop control variable and will be assigned each generated value, for which the ‘body og
‘for loop’ will be executed.
Practical Implementation-15
To calculate and display the factorial of an inputted number.
essai
[8 pam itey- eapin Tramthoy 8S)
'F Bython progran to accept a number from a user and print factorial of that nunbe:
[nun =int ( input ("enter non negative no to take factorial of : *))
fact =1
foe 3" in range aun):
fect = fact *(ie0)
print ("eactorial of *,mum ,"= ',£2¢8)
wsexxeexOutput of the programs+stssss
UB poeses oe ae 5 —
Fi Edel Op _Window Hp
feython 3.6.5 (v3.6.5:£59c0992b4, Mar 28 2018, 16:07846) [MSC v.1900 32 bit (int -|
Jel)} on win32
‘Type “copyright”, "credits" or "license()" for more information.
>>>
sc=sa=== RESTART: C:/Chapter $/prgm_16.py =--======
Jenter non negative no to take factorial of : @
8 = 40320
Factorial of
>>>,
Computer Science with Pythor
5.18 eoCMe Cc)
+ The or o0P In Python Is used to iterate values from range of values, strings lists, tuples or dictionary.
+ ‘else’ statement Is optional and will be executed after all the Iterations of for loop are over.
‘+ Repeated execution of a set of statements is called iteration.
+ The loop variable contains the highest value of the list after ‘or loop is over.
+ Value of for oop varlable cannot be defined beforehand
You must have observed that in the above examples we have used the range() function which
generates the values as 1, 2, 3, 4... and so on till the limit defined in the loop statement, We shall
now discuss range() function in detail.
range() Function in for loop
‘The range() is a built-in function in Python and is used to create a list containing a sequence of
numbers starting with the start and ending with one less than the stop. We have already used
this function in the previous Practical Implementation.
syntax:
xange([start], stop{, step})
Here, the parameters are defined as:
+ start: It defines the first value of the initial
0 (zero).
* stop: It marks the end of the iterations in a for loop. The iteration will repeat
one less than the stop value,
ration of the for loop. By default, it is set to
it reaches
+ step: Itis used to update (Increase or decrease) the loop variable by a given value. If the step
value is not provided, the value of the loop variable will be incremented by 1 (by default).
The start and step parameters are optional. By default, the list starts from 0 and in every
iteration, it is incremented by one but we can specify a different increment value by using the
step parameter. range() is often used in for loops.
For example,
Command Values generated
35> eange (10) (0, 1,2, 3, 4, 5, 6 7, 8, 91
>>> range (I, 11) (1, 2, 3, 4 5, 6 7, 8, 9, 101
>>> list (range(2, 10)) | (2, 3) 4) 5 6 7, & 9)
start value is given as 2
>>>list (range (0, 30, 5)) | {0, 5, 10, 15, 20, 25)
istep value is 5 and start value is 0
>o>list (range (0, -9, -1)) | (0, -1, -2, 3, ~4, -5, -6, -7, -8)
fetep value is -1. Hence, decreasing
#sequence is generated
‘The arguments of range() function must be integers. The step parameter can be any positive or
Regative integer other than zero.>
For example,
Ua poosiatey-Chynonino seeders) ~ TERT
i pragtan to" Greonatrate’ range ( functTon
orm An rangosyt
petnt(n* 10)
eT
mation.
RESTART: Ct/python36/prog_seLect3
Practical Implementation-16
Program to find the sum of the series:
S=14x4x74xF4x4 ex”
[SEES UTR RECRERRERERRES
| feces ee dint am of steer =
pHloattinpse nce he geiee oe)
fincnpue inter ine ralee oe°8 oy <0
re
Ee a in rangecnen:
4
i
»
RESTART: :/Users/preeti /appData/tocal,
PY
inter the value of x13
inter the value of n (for x**n):5
Sun of first 5 terms: 964.0
print ('Sun of tizstt
5.6.2 while Loop
A while statement in Python executes a block of code
repeatedly as long as the test/control condition of the
loop is true. The control condition of the while loop is
executed before any statement in the body of the loop
is executed. If the condition is true, the body of the loop
is executed. Again the control condition of the loop is
tested and the loop continues as long as the condition
remains true. When the test outcome of this condition
becomes false, the loop is not entered again and the
control is transferred to the statement immediately
following the body of the loop as shown in the flow
chart given in Fig. 5.11. Fig. 5.11
Syntax of while loop:
while :
Body of while
else: # optional
Body of else
5.20 ee> ‘while’ isa reserved word,
» test-expression is the condition to be checked for true/false value.
> ‘Body of while’ consists of single or multiple statements.
‘else’ is optional and executed when test condition evaluates to false.
‘Example 1: ‘Output
count = 1 1
hile count 2
print (count) 3
count += 1 4
5
‘Example 2: ‘Output:
n= int(input(" Enter a number to find|Enter a number to find its factor : 6
its factor : ")) 1236
print (1, end=" ')
# one is a factor of every number
factor = 2
while factor <= n/2;
ifn & factor == 0;
print (factor, ends" +)
factor += 1
print(n, end=" *)
# every number is a factor of itself
Note that body of the loop is indented with respect to the while statement. Similarly, the
statements within if are indented with respect to positioning of if statement.
Practical Implementation-17
Illustrating the concept of while loop statement.
[B pram i0py-Gicnape Sorgmi0py GS)
Tie_tat_FerRon_Gplon Window ep
lft Python program to illustrate while loop statenent
counter = 0
jwhile counter < 3: statement
print ("Inside loop") statement2
counter = counter + 1 statenent3
‘saxxeexxOutput of the program#rreess
dhe Sei Los sa enol
[ak Bboy Oper Vinson Hep )
Python 3.6.5 (v3.6.5:£5Se099%b8, Mar 28 2018, 1610746) [WSC v.1900 32 BIE Cin
/te1)) on wina2 7 7
Type “copyright, “credits” or “License()" for more information.
wenene= RESTART: C:\chapter 5\prgm_10.py ===emem=
In the above program, loop control variable ‘counter’ i initialized with 0, It checks forthe yay,
of counter up to 3, the loop shall be executing till this value. Every time the loop gets executey,
the message “Inside loop” gets displayed, followed by incrementing the value of counter in gt
iteration. Thus, this loop shall iterate for three times and shall terminate as the value f coun
becomes 3.
Ti now, we have discussed the while loop construct without the use of else part. Now we yy,
see how else construct performs well with the while loop.
Practical Implementation-18
Ilustrating the concept of while loop statement using else.
# body of e1se
Print ("The sun of first nine integers is: "/5)
(v3.6,5:£58c0932b4, Mar 28 2018, 16:07:46 “|
{300 32 bit (rntel)) on win32
[type "copyright", "credits" or "license()" for more in
Note that control will go to ‘else’ part only when condition of ‘while’ statement becomes false.
NOs
* The loop control variable must be updated inside the loop to avoid endless (infinite) loop.
* In Python, the body of the while loop is determined through indentation.
* Body starts with indentation and the first un-indented line marks the end of the loop.
* Python interprets any non-zero value as True. None and 0 are interpreted as False.
* Atleast one statement must be present in the loop body.
* ‘else's executed when test condition evaluates to false and is optional,
Using else Statement with Loops
Python supports an else statement to be associated with a loop statement.
» If the else statement is used with a for loop, the else statement is executed when the loop has
exhausted iterating the list.
> If the else statement is used with a while loop,
condition becomes false.
5.22 ‘a
the else statement is executed when theNow let us disi
Infinite Loop
what an infinite loop in Python is,
A loop becomes an infinite loop if
using while loops because of the
This results in a loop that never
@ condition never becomes false. You must use caution when
Possibility that this condition never resolves to a false value.
‘nds. Such a loop Is called an infinite loop.
Practical Implemen
fation-19
Iustrating the concept of Infinite Loop in while loop statement,
‘he concept of TnEinite Toop weing walle Toop construct”
{condition resuies
nuns ine (input renters sonbeea
Int ("You entered rm >
ing An an Aneinite Loop
n i
Print ("Good bye")
Python 3.6.8 (v3.6.5:£59¢0832ba, Nar 28 2018, 167%
00 32 pit (intelj} ‘on wins? a6) thse V.I8
Z¥pe "copyright", “credits” or "license()" for more information.
RESTART: C:\chapter S\prgm_i1.py
Enter a number ;100 i
\|vou entered: 100
Enter a number’ 200
||you ont
Bntor a number +600
‘you entered: 600
Enter a number
In the previous program, ‘var’ is a loop control variable and is assigned 1 before the loop starts
executing, Since loop control variable is not updated in the body of loop, it will not exit a loop
and becomes an infinite loop.
5.7 NESTED LOOPS
A loop may contain another loop as a part of its body. This loop inside a loop is called a nested
loop. Once the condition of outer loop is true, the control is transferred to the inner loop. The
inner loop is terminated first and then the outer loop terminates.
Syntax for a nested while loop:
while expression:
while expressio!
statement (s)
statement (s)
statement 2
Ina nested while loop, a while loop is defined inside another while loop.
Conditional and Looping ConstructsPractical Implementation-20
rating the concept of nested
while loop statement.
yale (2>=0)7
Body of
Otte logy
[] sees
a |_ simplify
Ah? geen: | ine
‘pedne(2,end=" ") | =
277 i ened inne oy
i 3 print 0p
Laan . eee!
seseesesutput of the programsre***
- 0 x
Drennan she ‘
feta Bony oe te ; Ges
A a et SeeSscOSaDN, Hak 7B DOVE, TEPOTHNS) HSS 79
eB 3e"bit. tantel)) on win’? epee eae
00 32, gney neredits" ox "License()
2 “= RESTART: C:/chapter 5/prgm_i7-py ===
rrr
pp
Explanation:
In the above program,
1. ‘isaloop control variable for outer loop and is assigned a value 2 before the loop execution
begins.
Test expression is checked for outer loop first.
The body of the outer loop is executed as test expression evaluates to true, it executes body
of the outer while, which contains another while statement, i.e, inner while.
{jis a loop control variable for inner loop and is assigned 2 before inner loop execution
, inner loop will be executed 3 times and will print 2 2 2, after which the inner loop
For
gets terminated.
After executing the rest of the body of outer loop, control goes to the next iteration of outer loop
and ‘i’ is incremented and becomes 1, again executes the body of outer loop (first executes the
inner loop). This process goes on till outer loop test expression remains True.
Syntax for a nested while loop:
for iterating_var in sequence:
for iterating_var in sequence:
statement (s)
statement (s)
statement 2
Like while, we can place for loop inside another loop as shown in Practical Implementation?
- Computer Science with yarpractical Implementation-21
ujustrating the concept of nested for loop statement.
[Bemnite-commeiemitwass ——
For iin range (1,4):
for j in range (1, 4+1):
Print (j,ende" ")
print ()
sse+++Output of the programssss4er+
Bisoisbe
fe $8 Sut Deny Ops Window Help
python 3.6.5. (v3.6.5 :F55c0S32U aE sF eau
zoned ab, Har 26 BOIS, TeOTe4e) (HSE v= 1800 t
Type "copyright", "credits" or "License()" tor more information.
/chapter §/prga_18 py —---s=eenenssesnaen==
Here, range function will generate value 1, 2, 3 in the outer loop. The inner loop will run for each
value of T used in outer loop. The value of outer loop variable will change only after the inner
Joop completely terminates,
‘+ Nested loop is one loop inside another loop.
+ Once the condition of outer loop is true, the control is transferred to the inner loop. First the inner
Joop is terminated and then the outer loop terminates.
‘+ The inner loop must have e different name for its loop counter variable so that it will not conflict with
the outer loop.
Practical Implementation-22
Write @ Python script to calculate the sum of the following series:
S = (1)+(142)+(142+3)+
| exes sare ChiaicelhseosahopanE oes ip se =) > ENE
+(14243+..0¢n)
Ta tt oma_her Opens teser Ip
| python script to calculate the a“
EEOC he Foalowing series’ S=(2)4(262)6(04262)+_ (te20340.4n) |
ip y >>>
Era tange daa RESTART: ¢:/Users/preeti
tereo jes1-py
EP Bin range ale How many terms? 7
vere Tem lt 2
pein (vers (a2), 11", term) Term 2:3
| Eamesterm fem 3: §,
[print (Sum of'yRy "terms 45:"/Sum) Fem 4: 10
Term 6:21
Term 7: 28
[Sur of 7 terns is:
Conditional and Looping Constructs ee 5.25
Ia 5.8 JUMP STATEMENTS
Rae Retreat to program and repeat tasks efficiently. In certain situations \,
Seaaeee ion occurs, a user may want to exit a loop (Come oUt of the too, Tah on,
SE come statements ofthe lop before continuing further in the loop. These requ) °
raken care of by use of break and continue control statements respectively, Python cy
Nr
these jump statements as a tool to give more flexibility to the Programmer to contra tr Mi
the gt
lotie
of loops.
5.8.1 break Statement
‘The break statement terminates the current loop, £2. the loop in which It appears, ang yg,
execution at the next statement immediately after the end of that loop. If break stateme®
inside a nested loop (loop inside another loop), break will terminate the innermost loop, ents
Syntax:
break
Enter loop.
for var in sequence:
# codes inside for loop
if condition:
break
# codes inside for loop
L_+# codes outside for loop
Spee cee eee ee
while test expression
je while loop
Bit Leop
# codes insil
if condition:
break
# codes inside while loop
Fig. 5.12: Flow Chart for break Statement
2 codes outside while loop
Practical Implementation-23
Illustrating the working of break statement,
La pamuttey - Cromote pgm 19 py BES
Tie_fat_ Footnotes Wedew HOP
¥ Use of break statement inside loop
for val in "string":
if val e= "i"?
break
print (val)
print ("over")
5.26
* Computer Science with python*eeeeeeeOutput of the prog
See ee me ——
2eeannewewnmenmnnmnen RERTART! C1/chaptor 8 /pgh_19.py emeneeeeneeneneencenen |
lover
pxplanation:
1, In this program, we iterate through the “string” sequence
2. When letter is “i,
breaks the loop.
3, Hence, we see In our output that all the letters get printed till“
terminates.
after which the loop
Ixprints ‘Over’ the last statement of the program which is not a part of the for loop.
practical Implementation-24.
illustrating the working of break statement,
[tt format Opten inde as
A fro5ram Eo dononstrate break stateacat
for mum in range (10):
un = num +1
Af num == 5:
Droak f
print (*Nun has value * + str(num))
Jprint Encountered break! Out of Leen")
& Pinon set
{4 Eo tht Dr Oates Haden Hap
[senrweeroennncnmenes RESTART! Ct /python36/pe [
log_selecté.py meermseerereareensce i
Nam has vaiue 1 |
Non has value 2 t
lwum nas value 3 i
t
‘Mun has value ¢
Encountered break!! out of 1oop
{tis dearly shown in the above program that when the variable num becomes 5, the break
statement is executed and the for loop is terminated.
Practical Implementation-25
llustrating the working of break statement with fo
Conent inside loop in for..else statement —
for val in "string"?
Sf val mm "int
break
cay)eeeseessOutput of the programssseeret
‘Po9cos32b4, Mar 20 2010, 16:07
)* for moro information.
Python 3.6.5 (v3.6.
to1)} on win32
type “copyright”, “erodits" or “14cons0
ee esranr: ce/chapter 5/PEgR_20-PY =*=ranmnanrancmennnny ||
e
Explanation:
“string” sequence.
1. In this program, we iterate through the
2, When letter is“ it breaks the loop.
3, Hence, we see in our output that all the letters get printed before “i.
Here, break statement terminates the whole block of ‘for..else’ and will not print “Bye”
Practical Implementation-26
Find the sum of all the positive numbers entered by the user. As soon as the user enters .
negative number, it stops taking in any more numbers from them and displays the sum,
# Program to denonstrate break statement
entry = 0
‘sun =0
[print ("Enter numbers to sum, negative number ends lis!
jwhile True:
entry = eval (input ())
if entry <0:
break
sum += entry
print ("sum =", sum)
+eseeee+Output of the program*s+sste+
Fle _Edt_Shel_Debug Options Window Hep
a sorsesssssses RESTART: Ct/python36/prog_select
Enter numbers to sum, negative number ends list:Sa SEE
Inthe above example, the condition of the
so, the body ofthe loop will always be em
never be false, the break statement is the
is executed when the user enters a negath
while loop will always be true as it is set to value “TUS
Ted and executed. Since the condition of the ‘while
only way to get out of this loop. The break statem
ive number.
yhen a break statement
When te countered during the execution of a program, the loop is
instantly terminated. Any statement(s) following the break within the body of the loop are then
5.8.2 continue Statement
Hae ection, thus claw 8 eRcountered, the control jumps to the beginning of the loop for
neat iteration, thus skipping the execution of statemerre inside the body of loop for the current
iteration. As usual, the loop condition is checked to see if the loop should continue further or
terminate Hine Condition ofthe loop is still true, the loop Is enter sec ne nee
transferred tothe statement immediately folowing the Ince ha
syntax:
continue J Emertoop
for var in sequence
codes inside for loop
—..
continue
# codes inside for loop
codes outside for loop
while test expression:
-——# codes inside while loop ee ee
if condition:
continue Fig, 5.13: Flow Chart for continue Statement
codes inside while loop
# codes outside while loop
Practical Implementation-27
llustrating the working of continue statement inside loops.
# Program to show the use of continue statement inside loops
for val in "string":
if val int
continue
print (val)
print ("over")
Pein and Looping Constructs ° oy
_— -neon st
ie (at She eboy Ope Window Hop =
Python 3.6.5 (v3.6.5:£59c0932b4, Mar 20 2010, 1610)
tel)) on win3z
[type “copyright, “credits” or “License ()" for more information,
YY eeeeenreeeeneeeenn,
eeeeenennnnnnennnmen RESTART! Ct/Chapter $/prgm_22.P:
(se v.1900 32
Explanation:
1. This program is same as the previous example
replaced with continue.
2. We continue with the loop if the string is “I’, not executing the rest of the block,
3. Hence, we see in our output that all the letters are printed except ‘Y"
‘After that, when the loop terminates, it prints ‘Over’ the last statement of the program which js
not a part of for loop.
except that the break statement has been
CTM: Like break, continue statement is within the block of code under the loop statement, usually
preceded by an if statement.
5.8.3 pass Statement
It is used when a statement is required syntactically but you do not want any command or code
to execute.
‘The pass statement is a null operation; nothing happens when it executes. The pass is also useful
in places where your code will eventually go but has not been written yet, However, nothing
happens when pass is executed. It results in no operation.
‘Syntax:
pass
Suppose we have a loop or a function that is not implemented yet but we want to implement it
in the future. It cannot have an empty body. The interpreter would complain. So, we use the pass
statement to construct a body that does nothing.
Practical Implementation-28
Illustrating the working of pass statement.
(Rae ee)
[goa bi Remsen Cpls Winton — Hl Ss oe Soe =
# pass is just a placeholder for any functionality to be added later.
Sequence = {'p's ‘a, 's'y 's'}
for val in sequence:
passGonienonuenn yy
he step-by-step solution to a given problem,
» The statement is a decision-making statement.
® The looping constructs while and for statements allow sections of code to be
* forstatement iterates over a range of values or a sequence.
> The statements within the bo
is fase,
executed repeatedly,
Gy of a while loop are executed over and over until the Condition of the while loop
* Whe condition ofthe while loop sitll false, the body isnot executed even once.
> The statements within the body of the while loop must ensure that the condition eventually becomes false;
stherwise, the oop will Become an infinite loop, leading to» logic een ic the program,
* loop contained within another loop is called a nested loop,
* The break statement immediately exits loop, skipping the rest ofthe body ofthe loop. Execution continues with
‘he statement immediately following the body ofthe loop,
* When a continue statement is encountered, the control jumps to the beginning of the loop for next iteration,
» The pass statement
a null operation; it does nothing,
Bisa