0% found this document useful (0 votes)
7 views62 pages

PY 07 Repetition 1

The document discusses repetition control structures in programming, particularly in Python, including the use of for-loops and the range() function. It provides examples of tasks such as printing 'Hello World' multiple times and converting Fahrenheit to Celsius. Additionally, it covers the concept of factorial and how to compute it using an accumulating algorithm.

Uploaded by

singhapad.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views62 pages

PY 07 Repetition 1

The document discusses repetition control structures in programming, particularly in Python, including the use of for-loops and the range() function. It provides examples of tasks such as printing 'Hello World' multiple times and converting Fahrenheit to Celsius. Additionally, it covers the concept of factorial and how to compute it using an accumulating algorithm.

Uploaded by

singhapad.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Control structure:

Repetition - Part 1
01204111 Computers and Programming

Chalermsak Chatdokmaiprai
Department of Computer Engineering
Kasetsart University

Cliparts are taken from http://openclipart.org


Outline
➢Repetition Control Flow
▪ Task : Hello world n times
▪ Definite loops – the for statement
▪ The range() function
➢Programming Examples
▪ A conversion table : Fahrenheit to Celcius
▪ The factorial function
➢More About Strings
▪ String indexing
▪ The len() function
▪ Strings are immutable
▪ For-loops with strings : String traversals
➢A Numerical Example : Average of Numbers

2
Fundamental Flow Controls
We have already
• Sequence learned and used
these three
• Subroutine control structures.

• Selection (or Branching)


• Repetition (or Iteration or Loop)

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

•variable after for is called the loop index.


It takes on each successive value in sequence in
the order they appear in the sequence.
•The sequence can be one of the Python
sequence objects such as a string, a list, a tuple,
or a range of integers from the built-in function
range().
8
How the for statement works
for variable in sequence :
code_block
more items in F
sequence
?
T
variable = next item

The number of times


the code_block is code_block
executed is precisely
the number of items
in the sequence.

9
Hands-on Example
The variable c is
the loop index.

>>> my_string = 'python' The variable my_string


produces the sequence
>>> k = 0 'p', 'y', 't', 'h', 'o', 'n'.
>>> for c in my_string:
k = k + 1
print(f'round {k} : c is {c}')

round 1 : c is p The code block to


round 2 : c is y be repeated for
Output each value of c.
round 3 : c is t
round 4 : c is h
round 5 : c is o
round 6 : c is n Run in pythontutor

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}')

round 1 : i is 10 The code block


round 2 : i is -3.5 Output to be repeated for
each value of i.
round 3 : i is py
round 4 : i is True Run in pythontutor

Don't worry about list objects now.


We'll study them in detail in the near future.
11
Hands-on Example The variable i is
the loop index.
The object range(4)
generates the sequence
>>> k = 0 0, 1, 2, 3
>>> for i in range(4):
k = k + 1
print(f'round {k} : i is {i}')

round 1 : i is 0 The code block


round 2 : i is 1 Output to be repeated for
round 3 : i is 2 each value of i.
round 4 : i is 3

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

values in the sequence


(in left-to-right order)
When step
is negative +step +step +step +step +step
...
stop start

values in the sequence


(in right-to-left order)
14
Hands-on Example To see the type of
object range()
>>> type(range(-4,14,3))
<class 'range'> This doesn't show the sequence
>>> range(-4,14,3) generated by range().
range(-4, 14, 3) Use the built-in function list() to
>>> list(range(-4,14,3)) show the sequence.
[-4, -1, 2, 5, 8, 11]
Try a negative step.
>>> list(range(14,-4,-3))
[14, 11, 8, 5, 2, -1] produces the empty sequence
>>> list(range(5,3,1)) because step is positive and start
[] is not less than stop.
>>> list(range(3,5,-1)) produces the empty sequence
[] because step is negative and
>>> list(range(3,3,2)) start is not greater than stop.
[]
>>> list(range(3,3,-2)) Notice that in all cases,
[] the stop value will never appear
in the generated sequence.
>>>
15
Hands-on Example : start and step can be omitted
>>> list(range(3,8,1))
[3, 4, 5, 6, 7] If step is omitted,
>>> list(range(3,8)) the default step is 1.
[3, 4, 5, 6, 7]
>>> list(range(0,5)) If start is also omitted,
[0, 1, 2, 3, 4] the default start is 0.
>>> list(range(5))
[0, 1, 2, 3, 4] So range(4) is the
>>> for i in range(4): same as range(0,4)
print('i is', i) and range(0,4,1).

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
---------- -------

Do those print statements above


still puzzle you?
21
If so, let's do some experiments to
demystify them:
def test_print(): >>> test_print()
print('12345678901234567890') 12345678901234567890
print(f"{'python':>10}{'idle':>10}") python idle
print(f"{'python':<10}{'idle':<10}")
python idle
print(f"{'python':^10}{'idle':^10}")
python idle
cel = 32/3
print('12345678901234567890') 12345678901234567890
print(f"{cel:>10.1f}{cel:>10.3f}") 10.7 10.667
print(f"{cel:<10.1f}{cel:<10.3f}") 10.7 10.667
print(f"{cel:^10.1f}{cel:^10.3f}") 10.7 10.667
print('12345678901234567890') 12345678901234567890
>>>
Left-justification is the
Right-justification is the
default for strings, so
default for numbers, so
the symbol < can be
the symbol > can be
omitted here.
omitted here.

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}")

for fah in range(start, end, step):


cel = (5/9)*(fah-32)
print(f"{fah:12}{cel:12.1f}")

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.

>>> Now, can you explain why our factorial(n)


returns correct results when n = 0 or 1 ?
32
33
String Indexing:
Accessing Characters in a String
➢ A Python string is an object of type str, which
represents a sequence of characters.
➢ We can access each individual character in a
string with an expression (type int) in the
bracket operator []. The expression in the
bracket is called a string index.

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

>>> greet = 'Hello Dan'


>>> greet >>> type(greet)
'Hello Dan' Both of them
<class 'str'>
>>> greet[0] are of type str.
>>> type(greet[4])
'H' <class 'str'>
>>> greet[4]
'o'
>>> print(greet[1], greet[4]+greet[8])
e on
35
String Indexing:
Accessing Characters Within a String
greet H e l l o D a n
0 1 2 3 4 5 6 7 8
>>> greet = 'Hello Dan' greet[1] is a string object so it can
>>> letter = greet[1] be assigned to a variable.
>>> letter
'e' String indexes can be any expressions of type int.
>>> k = 1
>>> greet[k]
'e' >>> 'python'[0]
'p'
>>> greet[k+5] Indexing also works
'D' on string literals.
>>> "python"[3]
>>> greet[2*k+5] 'h'
'a' >>> 'python'[k+2]
>>> greet[1.5] 'h'
TypeError: string indexes must be integers
36
Length of a String: The Built-in Function len()
greet H e l l o D a n
0 1 2 3 4 5 6 7 8
>>> greet = 'Hello Dan' The built-in function len() returns
>>> len(greet) the length of its string argument.
9
>>> len("I'm happy.") The last index of
greet is 8, not 9.
10
>>> greet + 'ny!'
>>> length = len(greet)
'Hello Danny!'
>>> length
>>> len(greet + 'ny!')
9
12
>>> lastchar = greet[length]
IndexError: string index out of range
>>> lastchar = greet[length-1]
>>> lastchar
'n' Correct index of
the last character.
37
Indexing from the right side: Negative indexes
greet H e l l o D a n
0 1 2 3 4 5 6 7 8
You can use negative -9 -8 -7 -6 -5 -4 -3 -2 -1
indexes to index
backward from the Notice the positive indexes that
end of the string. refer to the same positions as
their negative counterparts.
>>> greet = 'Hello Dan' >>> length = len(greet)
>>> greet[-1] last character >>> greet[length-1] last character
'n' 'n'
second-last second-last
>>> greet[-2] >>> greet[length-2]
character character
'a' 'a'
>>> greet[-9] first character >>> greet[0] first character
'H' 'H'
>>> greet[-len(greet)] >>> greet[length-len(greet)]
'H' 'H'
Also first character Also first character since
since len(greet) is 9. length-len(greet) is 0.
38
String Objects Are Immutable.
➢ Python string objects are immutable. That means the
characters within a string object cannot be changed.
A new string object 'Hello Dan' is created
>>> greet = 'Hello Dan' and then assigned to the variable greet.
>>> greet[6] = 'J' Expect to change Dan to Jan
TypeError: 'str' object does not support item assignment
>>> 'Hello Dan'[6] = 'J' This doesn’t work either.
TypeError: 'str' object does not support item assignment
>>> greet greet and the string 'Hello Dan' remain unchanged.
'Hello Dan'
>>> greet = greet + 'ny' A new string object 'Hello Danny'
is created and then assigned to
>>> greet the variable greet.
'Hello Danny'
Note that the variable greet has changed its binding
twice by assignment, but the two string objects,
'Hello Dan' and 'Hello Danny', can never be changed.
39
40
String Traversal
➢ Lots of computations involve processing a string
one character at a time in this pattern:
1. Get a string
2. Repeat from the beginning until the end of the string:
▪ Get next character
▪ Do something with the character

➢ This pattern of processing is called a traversal.


➢ In Python, one way to implement a string
traversal is by using a for loop.

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}/')

The symbol ; allows two or more


statements on the same line
42
Traversal Example: Spreading Out a String
Without using a loop, we may But since a string is a sequence type
write a python program to like a range() object, we can use
traverse the string assigned for statements with strings in a
to a variable text like this: similar way:

text = 'a dog' text = 'a dog'


c = text[0]; print(f'/{c}/') for c in text:
c = text[1]; print(f'/{c}/') print(f'/{c}/')
c = text[2]; print(f'/{c}/')
c = text[3]; print(f'/{c}/')
c = text[4]; print(f'/{c}/') Both work
The symbol ; allows two or more effectively
statements on the same line the same!

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.

text = 'a dog' text = 'a dog'


c = text[0]; print(f'/{c}/') print(f'/{text[0]}/')
c = text[1]; print(f'/{c}/') print(f'/{text[1]}/')
c = text[2]; print(f'/{c}/') print(f'/{text[2]}/')
c = text[3]; print(f'/{c}/') print(f'/{text[3]}/')
c = text[4]; print(f'/{c}/') print(f'/{text[4]}/')
Thus another version
of spread_str(text) This suggests that we can
def spread_str(text): also do this task by looping
"""print text, over the string indexes.
one char per line within ()""" Recall that the indexes of
for i in range(len(text)): any string s are in the range
print(f'/{text[i]}/') 0, 1, 2, …, len(s)-1
>>> s = 'a dog'
>>> list(range(len(s)))
[0, 1, 2, 3, 4]
45
Two equivalent implementations
def spread_str(text):
"""print text, one char per line within //"""
for c in text:
print(f'/{c}/')

Which one do you prefer?

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.

text = 'pete' This repetition


count = 0 is exactly the
c=text[0]; if c=='e': count = count+1 for loop:
c=text[1]; if c=='e': count = count+1
c=text[2]; if c=='e': count = count+1 for c in text:
c=text[3]; if c=='e': count = count+1 if c == 'e':
print(count) count = count+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.

print(f'The average of {n} number(s) is {avg}')


52
The function average(n)
❖ Algorithm of average(n):
▪ Gets the count of numbers n as its parameter.
▪ Reads each of the n numbers and calculate the sum:
sum = number1 + number2 + … + numbern
▪ Calculates the average with:
average = sum / n
Translate it
▪ Returns the average. into Python

def average(n):

? The hard part to be


figured out next
return sum/n
A new variable average is not needed
53
Accumulating Algorithm Once Again
▪ Reads each of the n numbers and calculate the sum:
sum = number1 + number2 + … + numbern
➢ sum = 0 Transform the sum formula into
➢ Read number1; sum = sum + number1 an accumulating algorithm.
➢ Read number2; sum = sum + number2
➢ sum = 0
➢ ...
➢ Repeat n times:
➢ Read numbern; sum = sum + numbern
• Read a new number into
Then make it a loop of n iterations. the variable number
• sum = sum + number
Notice that only one variable number
is enough for all numbers. Then translate it
into Python
sum = 0
for i in range(n):
number = float(input(f'Enter number #{i+1}: '))
sum = sum + number
54
average()- Complete
❖ Algorithm of average():
▪ Gets the count of numbers n as its parameter.
▪ Reads each of the n numbers and calculate the sum:
sum = number1 + number2 + … + numbern
▪ Calculates the average with:
average = sum / n
▪ Returns the average. Translate it
into Python
def average(n):
sum = 0
for i in range(n):
number = float(input(f'Enter number #{i+1}: '))
sum = sum + number
return sum/n
55
Average of Numbers – Complete Program
How many numbers? 4
import sys Enter number #1: 12
Enter number #2: 11.5
def average(n): Enter number #3: 13
Enter number #4: 10.5
sum = 0 The average of 4 number(s) is 11.75
for i in range(n):
number = float(input(f'Enter number #{i+1}: '))
sum = sum + number
return sum/n How many numbers? 0
Nothing to do. Bye!

# ---- main ---- #


n = int(input('How many numbers? '))
if n <= 0:
print('Nothing to do. Bye!')
sys.exit()
avg = average(n)
print(f'The average of {n} number(s) is {avg}')
56
57
Conclusion
•In computer programs, repetition flow control (also
called iteration or loop) is used to execute a group
of instructions repeatedly.
•In Python, a repetition flow control can be
expressed by a for-statement which allows us to
execute a code block a definite number of times.
•We can use a for-statement to iterate over any of
the Python sequence objects such as a range of
integers, a string, a list, etc.

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

range(start, stop) range(start, stop, step)


exactly the same as generates successive integers:
range(start, stop, 1) start, start + step, start + 2*step, …
If step is positive, If step is negative,
range(stop) the last element is the last element is
the largest integer the smallest integer
exactly the same as less than stop. greater than stop.
range(0, stop, 1)

60
Syntax Summary II
The list() function string indexing

list(range(start, stop, step)) str[0] first character


list(range(start, stop))
str[i] (ith-1) character
list(range(stop))
str[len(str)-1] last
Returns a list object defined by the character
successive integers generated by range()
str[-1] last character
The len() function second-last
str[-2]
character

len(string) str[-len(str)] first


character
Returns the length of
its string argument
61
Major Revision History
• September, 2017 – Chalermsak Chatdokmaiprai
◦ First release
• March 16, 2019 – Chalermsak Chatdokmaiprai
◦ Fixed minor typos
• February 2, 2020 – Chalermsak Chatdokmaiprai
◦ improved explanations here and there
• January 14, 2021 – Chalermsak Chatdokmaiprai
◦ Minor correction and improvement

62

You might also like