PY 07 Repetition 1
PY 07 Repetition 1
Repetition - Part 1
01204111 Computers and Programming
Chalermsak Chatdokmaiprai
Department of Computer Engineering
Kasetsart University
2
Fundamental Flow Controls
We have already
• Sequence learned and used
these three
• Subroutine control structures.
3
Schematic View of Flow Controls
Sequence
Subroutine Repetition
Selection
4
Repetition Flow Control
•Computers are often used to do repetitive tasks
because humans don’t like to do the same thing
over and over again.
•In computer programs, repetition flow control is
used to execute a group of instructions repeatedly.
•Repetition flow control is also called iteration or
loop.
•In Python, repetition flow control can be expressed
by a for-statement or a while-statement
that allow us to execute a code block repeatedly.
5
Task: Hello World n times
•Write a function hello(n) to write Hello World!
n times, where n 0 is the input. After that, write
Goodbye! once. >>> hello(10)
>>> hello(3) Hello World!
Hello World! Hello World!
Hello World! Hello World!
Hello World! Hello World!
Goodbye! Hello World!
>>> hello(0) Hello World!
Goodbye! Hello World!
>>> hello(1) Hello World!
Hello World! Hello World!
Goodbye! Hello World!
Goodbye!
6
The function hello(n) – Steps
❖ hello(n): How can we do
➢receive n as its parameter. this repetition in
➢repeat n times: Python?
• write 'Hello World!'
➢write 'Goodbye!'
def hello(n):
for i in range(n):
print('Hello World!')
print('Goodbye!')
7
Definite Loops: the for Statement
Python for variable in sequence :
Syntax code_block
9
Hands-on Example
The variable c is
the loop index.
10
Hands-on Example The variable i is
the loop index.
This list object
produces the sequence
>>> k = 0 10, -3.5, 'py', True
>>> for i in [10,-3.5,'py',True]:
k = k + 1
print(f'round {k} : i is {i}')
Run in pythontutor
12
The range() function
Python
Syntax range(start, stop, step)
•In its most general form, the range() function
takes three integer arguments: start, stop,
and step.
•range(start, stop, step) produces the
sequence of integers:
start, start + step, start + 2*step, start + 3*step, …
If step is positive, If step is negative,
the last element is the last element is
the largest integer the smallest integer
less than stop. greater than stop.
13
range(start, stop, step)
When step
is positive +step +step +step +step +step
...
start stop
i is 0
i is 1
i is 2
i is 3
16
17
Task: Print a Fahrenheit-to-Celcius Table
•Write a function to print >>> fah_to_cel()
a Fahrenheit-to-Celcius Fahrenheit Celcius
---------- -------
conversion table from 212 100.0
212 F to 32 F, 192 88.9
172 77.8
decremented in each 152 66.7
step by 20 F. 132 55.6
112 44.4
92 33.3
72 22.2
52 11.1
32 0.0
---------- -------
18
Print a Fahrenheit-to-Celcius Table - Ideas
➢ The formula to convert fahrenheit to celcius:
celcius = (5/9)*(fahrenheit-32)
➢ We’ll write a function fah_to_cel() to do the
task.
➢ We’ll use a for-loop in which the loop index holds
the fahrenheit values.
➢ The for-loop will iterate over a sequence from 212
downto 32 generated by range().
19
First, let's experiment with the range of
Fahrenheit values:
32 is missing!
>>> list(range(212,32,-20))
[212, 192, 172, 152, 132, 112, 92, 72, 52]
>>> list(range(212,31,-20))
[212, 192, 172, 152, 132, 112, 92, 72, 52, 32]
>>>
We should use one So now we've got
less than 32 so that a correct sequence
32 can be included running from 212
in the sequence downto 32.
20
The function fah_to_cel()
def fah_to_cel():
print(f"{'Fahrenheit':>12}{'Celcius':>12}")
print(f"{'----------':>12}{'-------':>12}")
>>> fah_to_cel()
Fahrenheit Celcius
for fah in range(212,31,-20): ---------- -------
212 100.0
cel = (5/9)*(fah-32) 192 88.9
172 77.8
print(f"{fah:12}{cel:12.1f}") 152 66.7
132 55.6
112 44.4
print(f"{'----------':>12}{'-------':>12}") 92 33.3
72 22.2
52 11.1
32 0.0
---------- -------
22
Next: Make fah_to_cel() more general
❖ Let's add three parameters: >>> fah_to_cel(32,100,20)
Fahrenheit Celcius
start, end, and step to control ---------- -------
the Fahrenheit values to be 32
52
0.0
11.1
printed. 72 22.2
92 33.3
>>> fah_to_cel(step=-20,start=100,end=0) ---------- -------
Fahrenheit Celcius >>> fah_to_cel(100,32,-20)
---------- ------- Fahrenheit Celcius
100 37.8 ---------- -------
80 26.7 100 37.8
60 15.6 80 26.7
40 4.4 60 15.6
20 -6.7 40 4.4
---------- ------- ---------- -------
>>> >>>
23
The generalized fah_to_cel()
def fah_to_cel(start, end, step):
print(f"{'Fahrenheit':>12}{'Celcius':>12}")
print(f"{'----------':>12}{'-------':>12}")
print(f"{'----------':>12}{'-------':>12}")
24
25
Task: Computing the factorial
❖ Suppose you have five pens of different colors to
give to five kids. How many ways are there to
give those five pens to those kids?
o Answer: 5*4*3*2*1 = 120 ways
This value is called the factorial of 5, or simply 5!
❖ More generally, the factorial is defined as a
function of nonnegative integers (0, 1, 2, …) such
that:
n! = n(n-1)(n-2)…(2)(1) when n > 0,
and 0! = 1
26
Task: Computing the factorial
❖ Let's write a Python function factorial(n)
to compute and return the value of n!
>>> factorial(5)
120
>>> factorial(3)
6
>>> factorial(1)
1
>>> factorial(0)
1
>>> factorial(10)
3628800
>>>
27
factorial(n): An Accumulating Algorithm
❖ How do we calculate 3! and 5! ?
o 3! = 3*2*1 = 6
o 5! = 5*4*3*2*1 = 120
❖ But the function factorial(n) must
work for every value of n, so we'll devise
an accumulating algorithm that works for
every value of n.
28
factorial(n): An Accumulating Algorithm
❖ How can we compute 4! by accumulating
results? Let's use a
o Start at 1 variable result
to hold the
o Take that 1, then 1*4 = 4 accumulating
o Take that 4, then 4*3 = 12 result.
o Take that 12, then 12*2 = 24
o Done!
Then, translate
o result = 1 our algorithm into
o result = result*4 Python statements
o result = result*3
o result = result*2
o return result
29
factorial(n): An Accumulating Algorithm
Notice that for 4!
o result = 1
this calculation is repeated
o result = result*4 3 times through the sequence
o result = result*3 4, 3, 2
o result = result*2 Therefore for n!
o return result this calculation is repeated
n-1 times through the sequence
o result = 1 n, n-1, n-2 …, 3, 2
o result = result*n
o result = result*(n-1) This repetition is
o result = result*(n-2) exactly the for-loop:
o ...
o result = result*2 for i in range(n,1,-1):
o return result result = result*i
30
factorial(n): from algorithm to code
o result = 1
o result = result*n
o result = result*(n-1)
o result = result*(n-2)
o ...
o result = result*2 And it's
o return result all done!
def factorial(n):
result = 1
for
for ii in
in range(n,1,-1):
range(n,1,-1):
result
result == result*i
result*i
return result
31
Wait a minute!
Does it work when n = 0 or 1 ?
When n = 0 or 1, the range() in
def factorial(n):
the for-statement becomes
result = 1 range(0,1,-1) or range(1,1,-1),
respectively.
for
for ii in
in range(n,1,-1):
range(n,1,-1):
result What are range(0,1,-1) and
result == result*i
result*i
range(1,1,-1)?
return result
>>> list(range(0,1,-1)) Can you explain why?
[]
And this is what happens
>>> list(range(1,1,-1))
when looping through
[] the empty sequence.
>>> for i in []:
Statements inside the loop
print("Yappadapadoo") don't get executed at all.
str_object[expression]
34
String Indexing:
Accessing Characters in a String
➢ The indexes of characters in a string are
numbered from the left, starting with 0.
H e l l o D a n
greet
0 1 2 3 4 5 6 7 8
41
Traversal Example: Spreading Out a String
➢ We want to write a program that prints each
character in a string, one per line, enclosed in //.
Without using a loop, we may
write a python program to
traverse the string assigned Output
to a variable text like this:
/a/
/ /
text = 'a dog'
/d/
c = text[0]; print(f'/{c}/')
/o/
c = text[1]; print(f'/{c}/')
/g/
c = text[2]; print(f'/{c}/')
c = text[3]; print(f'/{c}/')
c = text[4]; print(f'/{c}/')
43
Spreading Out a String : Generalization
Generalize and encapsulate
it into a function.
text = 'a dog'
for c in text: def spread_str(text):
print(f'/{c}/') """print text,
Test it. one char per line within //"""
for c in text:
>>> text = 'a dog'
print(f'/{c}/')
>>> for c in text:
>>> spread_str('a') Test it
print(f'/{c}/')
/a/ again.
/a/ >>> spread_str('')
No output
/ / >>> Why?
/d/ >>> dino = 'Rex'
/o/ >>> spread_str("T'" + dino)
/g/ /T/
/'/
/R/
/e/
/x/ 44
String Traversal: Looping Over String Indexes
These two blocks of code work effectively the same.
def spread_str(text):
"""print text, one char per line within //"""
for i in range(len(text)):
print(f'/{text[i]}/')
46
Traversal Example: Counting a Character
➢ We want to write a program that counts the
number of times a character appears in a string.
Suppose we want to count the This box traverses the string
number of 'e' in a string 'pete', from left to right. If the current
character is 'e', the variable
we may write a program like this:
count will be incremented by 1.
47
Counting a Character : Generalization
Generalize and encapsulate
text = 'pete' it into a function.
count = 0
def count_char(char, text):
for c in text: """counts the no. of times
if c == 'e': char appears in text"""
count = count+1 count = 0
print(count) for c in text:
if c == char:
Test it. count = count+1
return count
>>> count_char('a', 'anaconda')
3
>>> count_char('x', 'python')
0
>>> count_char(' ', 'I am happy')
2
>>> count_char(text='python', char='y')
1 48
Counting a Character : An Alternative
def count_char(char, text):
"""counts the no. of times
'char' appears in 'text'"""
Alternatively, we may count = 0
loop over string indexes for c in text:
with the same result. if c == char:
count = count+1
return count
def count_char(char, text): #version 2
"""counts the no. of times
char appears in text""" Which one,
count = 0 do you
for i in range(len(text)): think, is
if text[i] == char: simpler?
count = count+1
return count
49
50
Task: Average of Numbers
❖ Write a program to read n numbers and
calculate their average.
❖ The inputs of the program are the values of n
and all of the n numbers. n is a positive integer
and each number is a float number.
How many numbers? 4
Sample Enter number #1: 12
Run Enter number #2: 11.5
Enter number #3: 13
Enter number #4: 10.5
The average of 4 number(s) is 11.75
Sample How many numbers? 0
Run Nothing to do. Bye!
51
Average of Numbers – Topmost Steps
❖ Algorithm of the Main Routine:
▪ Read the value of n, making sure that n > 0
▪ Read each of the n numbers and calculate the average.
▪ Output the average.
Translate it
import sys
into Python
# ---- main ---- #
n = int(input('How many numbers? '))
if n <= 0:
print('Nothing to do. Bye!') We'll write the function
sys.exit() average() to do the
avg = average(n) read/calculate task.
def average(n):
58
References
• Think Python
◦ http://greenteapress.com/thinkpython2/thinkpython2.pdf
• Official reference on the for statement:
◦ https://docs.python.org/3/reference/compound_stmts.html#the-
for-statement
• Good tutorials for for-loops, range(), and string indexing:
◦ https://docs.python.org/3/tutorial/controlflow.html#for-
statements
◦ https://docs.python.org/3/tutorial/controlflow.html#the-range-
function
◦ https://docs.python.org/3/tutorial/introduction.html#strings
◦ http://www.python-course.eu/python3_for_loop.php
59
Syntax Summary I
sequence may be any Python
for statement
sequence object such as a string,
a range of integers, a list, etc.
for variable in sequence :
code_block The range() function
60
Syntax Summary II
The list() function string indexing
62