Chapter 5 Iteration
How to compute factorial ?
Factorial n! = n * (n - 1) * (n - 2) * ... * 2 * 1
Example
Object: compute 4!
Steps:
result = 1
result *= 2
result *= 3
result *= 4
print(result)
In sequential way?
What if n is a large number?
Iteration / Looping
—— process of executing the same section of code over and over
for statement
while statement

Iteration / Looping
—— process of executing the same section of code over and over
while statement
Iteration / Looping
—— process of executing the same section of code over and over
while statement
used for checking input (positive integer)
Iteration / Looping
—— process of executing the same section of code over and over
for statement
Iteration / Looping
—— process of executing the same section of code over and over
for statement
keyword: in
for i in 1,2,4,8:
print(i)
for i in range (1, 10, 2):
print(i)
for letter in 'word':
print letter
Iteration / Looping
—— process of executing the same section of code over and over
for statement
range (begin, end, step)
- begin is the first value in the range; if omitted, the default value is 0
- end is one past the last value in the range; the end value is always required and may not be omitted
- step is the amount to increment or decrement; if the step parameter is omitted, it defaults to 1(counts up by ones)
Iteration / Looping
—— process of executing the same section of code over and over
nested loop
print a multiplication table in the following form

Iteration / Looping
—— process of executing the same section of code over and over
nested loop
print a multiplication table in the following form

Iteration / Looping
—— process of executing the same section of code over and over
abnormal loop termination
break: implement middle-exiting loop control logic
continue: skips the rest of the body of the loop and immediately checks the loop’s condition
result: 11175
result: 5050
Iteration / Looping
—— process of executing the same section of code over and over
while/else & for/else


CS1302 Lecture 3 Chapter 5 (II)
By Chung Chan
CS1302 Lecture 3 Chapter 5 (II)
- 123