---
tags: Python Workshop 沈煒翔
---
# Lesson 3: Loops
## Recap (if-else statements)
### Giving grades
Given a score, print the grade for the student.
| Score | Grade |
| -------- | -------- |
| score > 90 | A |
| 90 >= score > 80 | B |
| 80 >= score > 60 | C |
| score < 60 | D |
```python
score = 77
if score > 90:
print("A")
elif score <= 90 and score > 80:
print("B")
elif score <= 80 and score > 60:
print("C")
elif score < 60:
print("D")
```
### Check military service
Given the gender, height, weight of a person, determine whether this person needs to join the army.
We know that only boys whose BMI is in between 16.5 and 31.5 need to join the army.
BMI = weight (in kg) / height^2 (in m)
BMI = 體重(公斤) / 身高^2 (公尺)
```python
gender = 'boy'
weight = 100 # in kg
height = 170 # in cm
if gender == 'girl':
print("Don't need to join the army")
else:
# calculate BMI here
BMI = weight / (height/100)**2
if BMI <= 31.5 and BMI >= 16.5:
print("Need to join the army")
else:
print("Don't need to join the army")
```
<!-- ### Calculate maximum discount
There's a pub running a promotion. The price of a bottle of beer is $10.
1. If you buy more than (including) 10 bottles, you can get 1 bottle for free.
2. If you buy more than (including) 20 bottles, you can get 2 bottles for free.
3. Either discount (1) and (2) can be used once.
Calculate the price you need to pay when you want to drink certain bottles of beer.
Sample inputs
```python
bottles = 22
cost = bottles * 10
if cost >= 220:
print(cost - 20)
elif cost >= 110:
print(cost - 10)
else:
print(cost)
``` -->
## Loop
The best part of computer programs is that they can do repeated task quickly and accurately. Loop is a control flow statement that allows code to be executed repeatedly.
### While loop
When the condition is true, the looping block is executed repeatedly.
```python
i = 0 # i is what we commonly use for the looping index
while i < 5:
i = i + 1
print(i)
#>>> 1
#>>> 2
#>>> 3
#>>> 4
#>>> 5
```
### Terminate condition
When writing loops, you need to make sure that the condition becomes ```False``` in the future so that the loop can be terminated. (unless you intend to do so).
If the condition is always true, then your program be stuck in an infinite loop and would not stop.
```python
i = 0
while i >= 0:
i = i + 1
print(i)
# program would not stop
```
### Exercise
Calculate arithmetic sequence 1 + 2 + 3 + ... + n
```python
n = 10
print(55)
```
### For loop
In addition to while loop, we can also use for loop to contruct a loop.
```python
for i in range(5): # range(5) is 0,1,2,3,4
print(i)
#>>> 0
#>>> 1
#>>> 2
#>>> 3
#>>> 4
```
Compared with while loop, for loop is more widely used and easier for other people to understand your code.
### Exercise
Calculate the geometric series 1 * 2 * 3 * ... * n
```python
n = 5
print(120)
```
### Range
In addition to using ```range(n)``` which means 0, 1, 2, 3, ..., n-1, we can set the start, stop, step size of the range. The syntax is:
```python
range(<start>, <stop>, <step=1>)
```
For example:
```python
for i in range(5, 10):
print(i)
#>>> 5, 6, 7, 8, 9
for i in range(10, 19, 3):
print(i)
#>>> 10, 13, 16
for i in range(3, 0, -1):
print(i)
#>>> 3, 2, 1
for i in reversed(range(3)):
print(i)
#>>> 2, 1, 0
```
## Loop control
### Manually stop the loop
Sometimes, instead of using the looping condition to stop the loop, you want to stop the loop yourself. You can use ```break``` to stop the loop.
```python
i_day = 0 # conventionally, looping index is named i something to preserve readability
earning = 0
while i_day < 10:
earning = earning + 200
i_day = i_day + 1
if earning > 1000:
break
print(i_day)
print(earning)
#>>> 6
#>>> 1200
```
### Manually skip the loop
Sometimes, you want to skip a particular loop block.
```python
# print all even numbers smaller than 10
for i in range(10):
if i%2 != 0: # "%" is mod (to get the remainder)
continue
print(i)
#>>> 2
#>>> 4
#>>> 6
#>>> 8
#>>> 10
```
### Exercise
Assume x>0 and x is an integer, find the minimum x that statisfies ```x^2 - 27x + 170 = 0```
```python
print(10)
```
Assume x>0 and x is an integer, find the minimum x that statisfies ```x^2 - 27x + 171 = 0```
```python
print("No solution")
```
## Nested Loops
Just like if-else statements, we can nest many loops together. For example:
```python
for i in range(3):
for j in range(2): # many people use i, j, k ...
print(i, j)
#>>> 0 0
#>>> 0 1
#>>> 1 0
#>>> 1 1
#>>> 2 0
#>>> 2 1
```
## Exercise
### Multiplication Table
Print Nine-Nine Multiplication Table (九九乘法表)
```python
for num1 in range(1, 10):
for num2 in range(1, 10):
product = num1 * num2
print('{}x{} = {}'.format(num1, num2, product))
```
### Prime numbers
Print all prime numbers smaller than 100.
Hint: prime numbers are integers with only two factors – themselves and 1.
```python
print(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
```
### Polynomial Optimization
Assume ```x``` is an integer in the range of [-10, 10], find the ```x``` the minimize ```y = x^2 + 4x + 1```. Print the value of ```x``` and ```y```.
```python
optimal_x = -10 # intialize it to the beginning of the range
optimal_y = optimal_x**2 + 4*optimal_x + 1
for x in range(-10, 11):
y = x**2 + 4*x + 1
if y < optimal_y: # we find a more optimal point
# update the optimal x and y
optimal_x = x
optimal_y = y
print('The optimal x is', optimal_x)
print('The optimal y is', optimal_y)
```