You are on page 1of 8

..

ArEMENTS 1N PYTHON
18 S
ITERATIVE •~

':=--
ILEARNING IN THIS CHAPTER] - --


- . - l~fi~~ Loop

L~p ...mse

::_ while ~ • = u: "basic concepts of Python, its functions, operator~


In the prevaous lesson, you rev,ewed the h It rative statements. In a ,.----- -- - ond~
statements. In this chapter, you will learn about t e e more statements •
ve to repeat one or •~:
program, there are situations when we ha . ·'.-! "
· g loops in programming. 'f
many times. This repetition can be carried out usm . .,, , ,
· h h help of a real-life example.
Let us understand the concept of a loop wit t e
. . n and take five rounds of the ......... ···~
fl -
tt »
Suppose, your mstructor instructs you to ru . . ...... ······ .... -........... ····•..
•ng you fix a starting point. On ...·· ··... · .
playground to warm up. Before you sta rt runm , / -.. .. -. . .
reaching the starting point again, you complete one round. Then you take th~ . _ \.. ) \
second round, and so on. This way you keep track of the number of rounds untrl ·--........::::::::·········· ..........
the process of taking rounds gets completed. ........................

Now, let us analyse the above example using programming to understand


looping.
Let us say the control variable is C. In this example, we have taken the initial value of C as 0. When you complete the
first round, the value of C becomes 1, after the second round, its value becomes C = C + 1, i.e., 1 + 1 =2, and soon.This
value will get incremented each time the process repeats. After incrementing, the control variable, Cwill be checke<
against the maximum number of the repetitions, which is 5 in this case.
Let us understand this example with the help of a Flowchart:

START

Take starting point as c

LetC =0

Are the number


of rounds
greater than or No C=C+l
equal to S (C>=S)? (Take more rounds)
t: Tfl4! for loOP eJ(ecutes and the range() function creates a se
stf'I Le-. 10 is assigned to the variable i. quence of values between 1Oto 19. The Initial
Z: ~squareof thevalue 10, i.e., 100 i.s printed.
• 1..1 • •

.grd~
,.. eydefault. the countervanaU(e 1s incremented by 1 a d .
n its square gets printed

-- lb! steP 3 contimJeS t:111 the last value in the sequence, i.e.,
. 19 is assigned
. to th ·
e variable I and its square is

,,,,_ (hange the step value or increment the value in the range() fu ti
~ u- - m~~;;:;7'f; ~.,_....,____ nc on by 3, see what happens:
~ 8. rit/l'PDOlltlll oca Type "copyrigh t" "
>>> ,
I fa Edit fOffl\lt Run Options Window
RESTART : C:/ U~er~ /
i range(l0 ,2 0 ,3): r 3 python/pylO a.py
prin t (i) 10
13
Here. value of i is
;naemented by 3 16 The variable is
everytime. 19 incremented by 3
at each step.
>>>
Figure 8.8: Changing Step Value in range(} function Output

Wflen you increment the step by 3, you will get the sequence [ 1o, 13, 16, 19].

SteP 1: The for loop executes and the range() function creates a sequence of values between 1oto 19. The initial
value, i.e., 10 is assigned to the variable i.
Step2; The value 10is printed.
•Step 3: The counter variable is incremented by 3, the next value is assigned to i, i.e., 13 is printed.
Step 4: The step 3 continues till the last value in the sequence, i.e., 19 is assigned to the variable i and gets printed.

M111::a

The value of the counter variable can also be decremented ton number of steps. For example:
foriin range (20,10,-3)

Program 9:To find the Factorial of a number.


Factorial of 5: 5 x 4 x3 x 2 x 1 = 120.
RESTART: C:\Users\ ADMIN\ AppData\ Lo9
r 3 pytb on\pyl 2 .py 7\
En ter a n umber: 5 \'
a•int (inp ut ( nEnter a number : " ) ) factoria l of t h e nurnbe :r l. 3 1 20 :\
The \\
t•l
>>> I ..i'
f:: i !.:'.".. range (1, a+l ): L-- - - - -- - -- -- -- ---~ ,lI
t•t •i
pnnt ( "The factorial of the number 13 " •! ) - - -- -- - -- --- - --•-·- -- - ·-· - - '

--:----·-- -- -- - - -- -.-'
Figure 8.9: Printing Factortal of a Num.,.r
Output
Stet> 1: The user is asked to enter a val ue f orvariablen
SteP 2: The variable a is initialised too. ·
St9P3: Thevariablebisinitialisedto 1.
5tep4: Initial value of a is printed.
SteP 5: Initial value of bis printed.
SteP 6: Now the for loop executes from 1 up ton+ 1.
step 1: The next value of the series is generated a d .
. . n printed by adding the rev·
Step 8: The value of b 1s assigned to a. P •ous two terms, I.e., c=a+b.

step 9: The value of c is assigned to b. Note, the value f d .


o a an bis updated every time wh th
step 10:The loop will terminate when the last value in th . . en e loop is executed.
.. e range, i.e., n+ 11s encountered .

• while LOOP
The while loop is the simplest of all looping structures. In general , th'is 1oop can be applied
• to a program h
number of iterations is not known beforehand. The while loop ke eps on executing . the block of statementw ere
I the
the specified test condition evaluates to true. as ong as
While loop has four main components:
INITIALIZATION
ltis used to assign an initial value to the loop control variable, e.g., a=1 o.
CONDITION/TEST EXPRESSION
This statement checks whether the loop body will be further executed or not. The loop keeps executing till the
condition or the test expression is true.
LOOP BODY f
It contains the set of statements that are required to iterate or repeat.

STEP VALUE
f \ \ e is achieved and the \ooµ term\nates.
This statement keeps updating the loop control variable sothat a ma va u
Remember
th th
You must provide an initial value to the loop variable to execute e \oop smoo \y ·

Syntax:
initialization

while<condition>:

loop body
updatjon
0
I f the following examples:
Let us understand the working of the while loop with th e he P
.r
Program t l : To print the flrst 1Onatural numbers.

-
>>>
llSTART: c 1 /Ua~ra/ ~
1
:i
1-0 3
while i <-10: •
5
print (1 )
1•1+1

7
ft

..__ -:, --- ---


0
10

f.'.fQur. a.11: Uuno whflt Loop to Print l'lret 10 Numbera


·------Output

Step 1: INtialfse thevartable I to 0.


St~p~ Check th~ condltfon whether I<• 10.
Step .3: ff f<•1Q, print the value off.
Step 4: Increment the value of I by 1, f.e., l=I+ 1.

StepS: This process will continue till the value of I ls less than or equal to 10. The loop will terminate once the
value off becomes greater than 1O.

Program 12: To print the square of numbers between 10 to 2O.

pyth o·n /pyl. 5. PY


file idit fsztmat ,Blan Ytindlw# 1.00
i-10 1.21
wcil.e i <2 0 : 144
print ( i* · ) 169
i += l 196
225
Square of a number 256
is calculated.
289
l, 324
l
J 361
>>> I
Figure 8.12: Square of Numbers Using while Loop
Output

Ste p 1: ThevariableHsassignedaninitialvalue, 10.


Step 2: The condition i<20 i.s checked.

Step 3: ff the condition evaluates to true then the statement prlnt(l*I) is executed.
Step 4: Each time the loop executes, the value of I is incremented by 1.

Step S: The control shifts back to the while loop. The while condition is checked again. If the condition is true th e
steps 3 a:nd 4 are repeated, and if the condition fs false., the whll~ loop terminates.
I
3 . To print the multiples of 3 and their sum (in th erange10to30).
ni 1 •

I .

12
lS
18
I 21
21
27
30
if"'
1
=
-
ot ell u:e 11:illtiple~ o f 3 in the r anqe 10 t o JO is : • , s) The
>>>
S\lll of all t he
1111.
l .
t iples of 3 in the range 10 to 30 i s : 117
'

I I
figu,....~ s.13·. Sum of multiple of 3 using while loop

The variable I is assigned an initial value, 1 O.


Output

step 1:
• The variables is assigned an initial value, O. It will store the sum of all them it· f
step 2 · u 1p1eso 3.
step . 3• The condition f<=30 is checked.

J step 4: ff the condition evaluates to true then the if statement checks whether the variable is a multiple of 3 or
I not.
I Step 5: tfthe condition is true then the counter variable is printed and is added to the previous value of s.
Step 6: Each time the loop executes, the value of i is incremented by 1.

Step 7: The control shifts back to the while loop. The while condition is checked again. If the condition is true
then steps 4,5 and 6 are repeated, and if the condition is false then the while loop terminates.

Step 8: The final value of sis printed.

Program 14: Toprintthetableof a number.


r 3 pyth on /py1 8. p y
Enter a number :6
file £dit 'FQ,mat Run Qptions Window 6 " 1 = 6
6 * 2 = 12
n =int (inp u t ( "En ter a number : " ) ) 6 * 3 = 18
6 * 4 = 24
i =l 6 * S = 30
w.t il e i <=lO : 6 • 6 = 36
p rin t(n , ' "' , i , 1 = 1 , n*i ) 6 1r 7 = 42
6 • 8 • 48
i+=-1 6 • 9 = 54
6 • 10 • 60
>>>

Output
Figure 8.14: Printing table of 6 using whlle loop

Step 1: The user is asked to enter a number of his choice.

Step 2: The initial value 1 is assigned to the variable i.

Step 3: The while condition 1<=1 Owill be checked. . . . d ,.


step 4: If the condition evaluates to true, the statements aft er the while condition are executt d and the P' o .uct

- - ~o~fn~a~n~d~i~
is~p~
ri~
nt~e~d:.,
· - -- - - - - - - - - - - - - - -- -- - - - -- : -
It
. \ _ \ _ , . ~ ' , , ' ~ " ' ~ ~ ~ ~ ~ ~ , ' ,\ t ~l\tt\ 1{
' \ ' \ \\\. \
,~',\\\'\~~~~ ~·~\\(.~1~ ~~~0 r,)lt~1,u\r•i l> ,~
Step 5: The value of I ls Incremented by 1.
Step 6: The control shifts back to the whfle loop. The while condition is checked again • If the condition is~
then steps 4 and 5are repeated and ff the condition Is false, the while loop terminates.

Program 15: To create a program displaying no output when the test condition is false.

3.7.0 {Y3.7.0:lbf9ccSog 3 .
1)) OD vill32 ' J
Type •capyript•, •credita• Ol: •li.,
>>> I

- - - - - RESTAU: C:/Uaeratsa:
>» I

return falH.
not execute

Ln:2 CotlO
Figure 8.15: FalH Test Condition In while Loop Output

In the above example, as the initial value of i, 10 is greater than 1, the condition will return false, and hence the loop
body will not be executed even once. Hence you do not get any output.

•>INANITE LOOP
An infinite loop (or endless loop) is a sequence of instructions in a computer program which loops endlessly. It
happens either due to the loop having no terminating condition or having the condition that can never be met. Let's

· • m 16: c:•: :ispla~ngen: op.


consider the following example:

5181
i•l O 5182
wh il e i>-1 :. 5183
print (i) 518"
S185
i+-1 Infinite loop SlH
S187 Totenninate
S188 an Infinite loop dose
5189 the interactive mode
5190 window.
5191
Ln;5 Coto 5192
Figure 8.16: Infinite Loop
Output

In the given example, as per the condition, the loop will continue until the value of I is greater than or equal to 1. In
the updation part, we are incrementing the value of I by 1 at every step and hence the loop variable I will always be
greater than 1. This means that at no time will the loop variable be less than 1 and hence the loop body will execute
Infinitely.

,,
', I , I
- ~-- ... ·~ .

,,,e ou t of the infinite loop, you have to tern,·•nate the lntera . - ~


\:I
]
fD ,o t1ve mode window. ct1ve mode or program execution by I .

r,

. '&f"l,wesinflniWl'·
·ttte ,ontral variable
.
does not get updated to a fl
nal value, the
condition remains true forever, and the loop

' LOOP···else
AfOf' 100P
or a while loop can have
.
an optional else bl ock as well. The el
fly i.e. if all the values m the sequence get used I se part Is executed If the loop t 1
,,ort1l3 • ' . n a standard w erm nates
. ated, Both the loops, 1.e., for and while loop can use I ay without the loop being forcef 11
rerrn'" . . e se part. Howev I
iock with the IOOP block. It IS 1ust a secure way to check that th I
u y
er, t Is not mandatory to have an else
t, e oop has terminated normally.

pro ram 17·· To print the sum of all even and odd numbers in a range.
g
tsfilt..&it
~ 1illllllf
-Wm bl.I . Wliliiiltn•
" Yf\N44 £4 @&@bb1
.-;..nc (input ( •Enter the lower limit:" ))
t>-int (input; ( •Enter the upper limit:" ))
even-0
odd-0
fo = i in range (a, 1:>+1) : , , , - - - - - - - - -
.1 f i 12--0 : The else part will be
even+-i executed when the loop
el!5e : terminates successfully.
odd+-i
print ( "Loop terminated successfully:" )
print ( "The sum of all the even numbers i.n the given series is: " , even)

_____________________________________
print ( "The :mm of all the odd numbers i.n the given series is:" , odd)

...
ln:8 Col:0
-
Figure 8.17: for... else

Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit (lnte •

l) I on win32
type •copyright•, •cretdita• or •11cenae () • tor mre 1ntormation.
>>>- - - RESTART: C:\Usua\Dineah nanr\Deakeop\Python\proo_9,PY
-
!llte.r the lower U :ait: 10
Enter the upper lilllit: 20
l,.oop teminated successfully: 90
The swn or all the even nuabers in uie given series u: 75
The swa O•f llll the odd numbers in the givell series u:
»> I

output
Prograrn 18· To rf h 00
· P ntt eserfes:4916.......... 1

. 1 of the :,er1.e:s . ) )
a•int ( input ( •£nte.r c.h e lower leve of the :series : "' ))
b-int ( input ( "'Enter tlle upper level
1.•a
w:tu.le i<-t>: The else part will be
C-(i*•2) executed when the loop
print (c, ' ' )

i.:-:1~ --======:.---
tenninates successfully.

e ls e :
print () I
print ( •Loop is terminated successfully• )

Figure 8.18: while .... else

- RESTART: c: /Users/AmllN/AppData/Local/Programs/Python/PYt.
Enter the lower level of the series: 2
Enter the upper leve.l of the seri.e s =10
4
9
16
25
36
49
64
81
100

Loop is tenni.nated successfully


>>> I

Output

O In Python, Iterative statements keep repeating a set of statements as long as the given ·
condition is true.
O Iterative statements are also known as loops.
There are two typesof It erative statements; for and while loop.

for loop is generally used when we have to repeat a task a specified number of times or within a given range.
The In operator checkswhether a given value is a part of the specified sequence.

The range() function produces a fist of a sequence starting with an Initial value up to a final value, updating ,
,afue at each step. 8ydefault, the value Is incremented by 1.

You might also like