0% found this document useful (0 votes)
8 views

05 Repetition Structures

Uploaded by

micklanape
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

05 Repetition Structures

Uploaded by

micklanape
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Repetition Structures

for loop, while loop


Learning Outcomes
● For loop
● While loop
loops in Python[1]
∙ It is rarely useful that a computer performs each operation only once;
we usually need it to repeat what it does.
− To do so, we need loops.

∙ Loops are one of the most important features in computer


programming languages.
− As the name suggests is the process that get repeated again and again.
− It offers a quick and easy way to do something repeated until a certain
condition is reached.

∙ Every loop has 3 parts:


− Initialization
− Condition
− Updation
3

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

Used when we want to skip one or


more statements in loop's body and
to transfer the control to the next
iteration.

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)

∙ This is a unique feature of Python and not found in most other


programming languages.
− The else clause in Python while loop is only executed when
your while condition becomes false.
− If you break out of the loop, or if an exception is raised, it 14
won't be executed.
14
else in while loop
x=5
while (x <=10):
print (x )
x = x +1
else:
You can see the condition is
print(x , " Inside Else")
(x<=10). Up to that condition,
the while block executed and the
∙ Output
5
final value of x=11.
6
Then the condition is false and
7
the control goes to else clause of
8
while loop and print the
9
10
statement.
11 Inside Else 15

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

• Write a program to input set N of marks of and output the


minimum, maximum and average marks.
Use a while loop
for loops[1]
∙ Used to execute some part of
the code a predetermined
number of times

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!".

So, this is equivalent to the code:


i = 0
print("Hello, World!")
i = 1
print("Hello, World!")
i = 2
print("Hello, World!")
i = 3
print("Hello, World!")
i = 4
24
print("Hello, World!")
24
for loop syntax
1) start with the keyword "for",
2) followed by the name of the variable that will be assigned all the values
through which we want to loop (or "_" if we don't need those values),
3) then a keyword "in",
4) then a list or something that acts like it (we'll see more examples
throughout the course), and
5) then a colon ":".

∙ As in while loop, do not forget the colon!


∙ Indentation ← Very Important! - Notice the indentation in the second line:
for i in range(5):
print("Hello, World!")
∙ All the commands with the same indentation "belong" to that loop.
25

25
Example
∙ Predict the output of the following program:

print("The first loop:")


for i in range(3):
print("Inside loop.")
print("And where is this? Inside or outside of the loop?")
print()

print("The second loop:")


for i in range(3):
print("Inside loop.")
print("And where is this? Inside or outside of the loop?")

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

n,m=eval(input("Enter values for n,m: "))


for _ in range(n):
s=""
for _ in range(m):
s+="*"
print(s)

∙ Similarly we can have break and continue in for loops also, as in


31
while loops.
31
for loop in list - example
∙ for loops are used extensively in ∙ Output
lists which we will cover later January
February
∙ Example March
April
months = ["January", "February", May
"March", "April", "May",
June
"June", "July","August",
"September", "October", July
"November", "December"] August
for mName in months: Spetember
print(mName) October
November
December 32

32
Exercise 2

• Write a program to input the marks of N students and


output the grade of each student, based on:
• A+: 80 – 100
• A: 70 – 79
• B: 60 – 69
• C: 50 – 59
• D: 40 – 49
• F: 0 – 39
Exercise 3

• Write a program that calculates the sum of the square of


all multiples of 3 between 0 and 100
Exercise 4

• Write a program that allows the input of an integer value


n and displays all multiples of 3 which are less than or
equal to n, as well as the sum of the square of these
values.
Exercise 5

• Write a program to use floating point arithmetic to add up


the reciprocals of all the integers up to and including the
input value n.
Exercise 6

• Write a program that allows you to input an integer value


n. If n is greater than 100, it displays the message ‘Wrong
Input’, otherwise it displays all factors of n.
Exercise 7

Fibonacci numbers are generated from the following


algorithm:
F =0
1
F =1
2
F =F +F for n>2
n n-1 n-2
Using a single for loop, write a program to display the first
15 such numbers.
Exercise 8

Write a program that continually prompts the user to enter


integers from the keyboard. The program terminates when
the integer entered is –5 or 0 or is greater than 8. Test your
program carefully to ensure that all the loop termination
criteria are met.
Acknowledgments
● DGT1039Y lectures notes by Dr. Shakun Baichoo, FoICDT

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy