05 Repetition Structures
05 Repetition Structures
3
loops in Python[2]
Update
4
while loops[1]
∙ Sometimes, it is not known ahead of the execution how
many times the loop will have to repeat its block. For
example:
− Load some numbers until a zero is loaded and do
something with them;
− Do something with number's digits (technically, we can
count the digits first, but it's a waste of time);
− Read the data as long as there is input (from a file,
standard input, etc).
− ...
5
5
while loops[2]
Using a ‘while’-loop code
n = int(input("n = "))
i = 0 # loop control variable
while i < n:
print(i)
i += 1 # update the loop control variable
Output
n=5
0
1
2
3 6
4 6
while loops[3]
∙ How does the ‘while’ loop work?
∙ Let us, as before, read the given code as if it was a sentence in regular
English language, taking into account that i += 1 stands for "add 1 to
i", i.e., "increase i by 1":
∙ while 𝑖 is less than 𝑛, print 𝑖 and increase it by one.
∙ And this is exactly how while-loops work:
1) check the condition,
2) if the condition is true, execute the loop's body and go back to
step 1,
3) if the condition is false, skip the body and continue the execution
behind the loop.
7
7
while loops[4]
while-loop syntax
∙ while-loops have the following elements:
1) start with the keyword "while",
2) followed by the condition that has to be
checked,
3) then a colon ":".
∙ Do not forget the colon!
8
while loops[5]
∙ Can we change how the loops run?
− Yes, we can break the loop earlier than it would
normally stop and we can skip parts of it - Python
provides two keywords that terminate a loop iteration
prematurely: break and continue.
− break leaves a loop.
− continue jumps to the next iteration.
9
break in while loop
break statement
Sometimes it's necessary to
exit from a Python while
loop before the loop has
finished fully iterating over
all the step values.
This is typically achieved by
a "break" statement.
10
10
break in while loop
x=10
while True:
print (x)
x+=2;
if x>20:
break When the condition x>20, the
print("After Break")
break statement executed and
immediately terminated the while
loop and the program control
∙ Output: resumes at the next statement.
10
12
14
16
18
11
20
After Break 11
continue in while loop
continue statement
12
12
continue in while loop
x=0
while x < 50:
x+=10
if x==30:
continue
print (x) We can see in the output
print("Loop Over") the 30 is missing. It is
because when the
∙ Output condition x==30 the loop
10 encounters the continue
20 statement and control
40 goes back to start of the
50 loop.
Loop Over
13
13
else in while loop
else clause
while (condition) :
statement(s)
else
statement(s)
15
else in while loop
x = 11
while (x <=10):
print (x )
x = x +1 The initial value of x=11
and condition is (x < =10).
else:
So there is no way to enter
print(x, " Inside Else") inside the while loop.
Hence, the control directly
∙ Output goes to else block of while
11 Inside Else loop and print the
statement.
16
16
Nested while loops
∙ A nested while loop is a loop within a while loop
− An inner loop within the body of an outer one.
∙ How does this work?
● The first pass of the outer while loop triggers the inner
while loop, which executes to completion.
● Then the second pass of the outer loop triggers the inner
loop again. This repeats until the outer loop finishes.
● Of course, a break within either the inner or outer loop
would interrupt this process.
17
17
Nested while loops
i=1
Output
while i <= 5:
1
j=1
12
while j <= i:
123
print(j, end = '')
1234
j += 1
12345
print()
i += 1
18
18
Infinite loop
● As the name suggests, an infinite loop runs forever.
− In the context of a computer programming, this means that the loops runs
until the program terminates.
− An infinite loop can be useful in a program that is always looking for
some kind of input.
− While it is waiting for the input, it can be sitting idle.
− We can program an infinite loop using Python while statement.
● If the condition of while loop is always True, we get an infinite loop.
● Example
# Press Ctrl + c to exit from loop
while True:
print ("This is an infinite Loop")
Output
19
This is an infinite Loop
19
This is an infinite Loop ….
Exercise 1
21
21
for loops[2]
∙ In Python, we often use the for-loop together with the range function
which pretends to return a list of numbers (it returns something more
complex, we can consider it a list for now).
∙ That function can be called as follows:
− range(n) -- numbers 0,1,…,𝑛−1;
− range(m, n) -- numbers 𝑚,𝑚+1,…,𝑛−1;
− range(m, n, s) -- numbers 𝑚,𝑚+𝑠,…,𝑚+𝑠𝑘
− , where 𝑘∈ℕ such that 𝑚+𝑠𝑘<𝑛≤𝑚+𝑠(𝑘+1).
● In other words, numbers from 𝑚 to 𝑛−1 with step 𝑠, but we
might not hit 𝑛−1, depending on the value of step 𝑠.
− Do not forget that the ending is not included, hence "−1"!
22
22
for loops[3]
for i in range(5):
print("Hello, World!")
∙ Output
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
23
23
for loops[4]
How does that code work?
∙ Let us read it as if it was a sentence in regular English language, taking into account
that range(5) acts as a list of numbers 0,1,2,3,4 :
∙ For i in (0, 1, 2, 3, 4), print "Hello, World!".
25
Example
∙ Predict the output of the following program:
26
26
for loop (Example)
∙ Write a program that inputs an integer 𝑛, then inputs 𝑛 numbers 𝑎1,𝑎2,…,
𝑎nand prints
27
27
Solution1
n = int(input("How many numbers do you want to summarize? "))
s = 0
for i in range(n):
x = float(input("Input a_" + str(i+1) + ": "))
s += x We use the variable i to
print(s) explain to the user which
number they have to
∙ Output input.
How many numbers do you want to summarize? 3 However, since range(n)
Input a_1: 17 traverses through
Input a_2: 13 numbers 0,1,…,𝑛−1 and
Input a_3: 19 we want then to be
49.0 1,2,…,𝑛, we used i+1 for
such a description.
28
28
Solution2
∙ We can avoid this extra addition by simply explaining to the range() function
that we want the numbers to start from 1 and go up to 𝑛 (i.e., numbers from 1,
strictly smaller than 𝑛+1):
n = int(input("How many numbers do you want to summarize? "))
s=0
for i in range(1,n+1):
x = float(input("Input a_" + str(i) + ": "))
s += x
print(s)
∙ Output
How many numbers do you want to summarize? 3
Input a_1: 17
Input a_2: 13 29
Input a_3: 19
29
49.0
Using for loop
str = "Python"
for c in str:
print(c)
∙ Output
P
y
t
h
o
n
30
30
Nested for loops
∙ We can have nested for loops just like nested while loops
∙ Example – Write a program to display a n x m rectangle of ‘*’
∙ Answer
32
Exercise 2