---
tags: Python Workshop 沈煒翔
---
# Lesson 2: Boolean data type + if-else statement
## Recap
Basic data types in Python
| Data type | Examples | Operators |
|------------------------|------------------------|----------------|
| Integer (int) | 0, 1, -3, 1000 | +, -, *, /, ** |
| Floating point (float) | 0.0, 5.3, 2e10 |+, -, *, /, ** |
| String (str) | 'hello', "Hi", "12345" | |
We can use `type()` to check the data type of the variable
```python
a = 5
print(type(a))
#>>> <class 'int'>
b = 15e4 # It means 15 with 4 zeros afterward.
print(b)
#>>> 150000.0
print(type(b))
#>>> <class 'float'>
c = a + 15.3 # Automatically cast to float. Just like real Math.
print(c)
#>>> 20.3
print(type(c))
#>>> <class 'float'>
d = 1 + 5 * 2 # Multiply/divison first, then addition/subtration. Just like proper Math.
print(d)
#>>> 11
print(type(d))
#>>> <class 'int'>
e = 50 / 3 # Also cast to float, like Math.
print(e)
#>>> 16.666666666666668 # some error caused by the precision limit of floating numbers.
print(type(e))
#>>> <class 'float'>
```
You can also change the data type of a variable using **casting**. **Python is a dynamic type language which means programmers should not worry too much about the typing.**
Also, using either int and float would not matter too much in most cases.
## Boolean datatype
It's either `True` or `False`. Only two values in this type.
```python
a = True
print(a)
#>>> True
print(type(a))
#>>> <class 'bool'>
b = False
print(b)
#>>> False
```
### Comparison Operators
| Operator | Meaning | Example | Output |
|----------|--------------------------|-----------|--------|
| == | Equal | 5 == 3 | False |
| != | Not equal | 5 != 3 | True |
| > | Greater than | 10.3 > 2 | True |
| < | Less than | 2 < -1 | False |
| >= | Greater than or equal to | 5 >= 5 | True |
| <= | Less than or equal to | 5 <= 4 | False |
### Logical Operators
| Operator | Meaning | Example | Output |
|----------|---------------------------------------|-------------|--------|
| and | True if both statements are true | 5<9 and 3<5 | True |
| or | True if one of the statements is true | 5<9 or 5>9 | True |
| not | Inverse the result | not 5<3 | True |
### Example
```python
iPhone13_price = 22900
hourly_rate = 150
work_hour = 300
# We can see if I am able to purchase the iPhone.
print(work_hour * hourly_rate > iPhone13_price)
#>>> True
# However, if I work too much I might die.
max_work_hour = 200
print(work_hour * hourly_rate > iPhone13_price and work_hour < max_work_hour)
#>>> False
# Another factor to consider is that whether I can ask my Dad.
have_dad = True
print(work_hour * hourly_rate > iPhone13_price and work_hour < max_work_hour or have_dad)
# "and" excuted before "or" so this is the same as
print((work_hour * hourly_rate > iPhone13_price and work_hour < max_work_hour) or have_dad)
#>>> True
```
Notice that I use smaller case for variable and use "_" in between words. You should follow my coding style as exact as possible.
## If-else statements
Normally the code is excuted sequentially. If-else statements let you control the flow of your program.
```python
score = 40
if score >= 60:
print("You passed!")
else:
print("Come again next year.")
#>>> "Come again next year."
```
1. ":" after the condition.
1. Indentation (use four spaces, or tab four spaces!)
Also, you can have multiple different conditions using `elif`
```python
score = 70
if score >= 90:
print("You got an A+")
print("Great work")
elif score < 90 and score >= 85:
print("You got a A.")
elif score < 60:
print("You failed.")
else:
print("Passed but try harder.")
```
### Exercise
Calculate how much tax this person have to pay. Assume 5% tax rate for income between [0, 10000], 10% tax rate for income more than 10000.
```python
income = 50000
print(5000)
```
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 |
Sample inputs
```python
score = 77
print("C")
```
### Nested if-else statements
You can add as many if-else statements as you want.
```python
iPhone13_price = 22900
hourly_rate = 150
work_hour = 100
max_work_hour = 500
have_dad = True
if work_hour > max_work_hour:
print("Died working too hard")
else:
print("Your survived and have good kidneys.")
if work_hour * hourly_rate > iPhone13_price:
print("You bought the iPhone 13.")
elif have_dad: # this is the same as have_dad == True
print("Your Dad bought the iPhone for you.")
else:
print("No iPhone QQ")
work_hour = work_hour + 10000
```
## Exercises
### Pass exam
You are taking the IELTS exam and there are four tests: reading, writing, listening, speaking test. Among the four tests, you need to have an average not less than 7.5 and none of the tests should be less than 7.0 to pass the exam.
Determine whether this person passes the exam?
```python
test1 = 8
test2 = 7
test3 = 7.5
test4 = 6
print("Didn't pass")
```
### Classifying triangles
We know that a triangle is either acute (銳角), right (直角), or obtuse (鈍角). Acute means that all angles in the triangle are less than 90 degree. Right means that one of the three angles is 90 degree. Obtuse means that one of the three angles is over 90 degree.
Given the length of the three sides of a triangle, determine whether the triangle is acute, right, or obtuse.
Sample inputs:
```python
length_A = 3
length_B = 4
length_C = 4
print("acute triangle")
length_A = 3
length_B = 4
length_C = 5
print("right triangle")
length_A = 3
length_B = 4
length_C = 6
print("obtuse triangle")
length_A = 3
length_B = 4
length_C = 7
print("triangle cannot exist")
```
Sample code:
```python=
# inputs
length_A = 3
length_B = 4
length_C = 5
```
<!-- # Take-home practices -->
### 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 (公尺)
Sample inputs
```python
gender = 'boy'
weight = 100 # in kg
height = 170 # in cm
print("Don't need to join the army")
gender = 'girl'
weight = 70 # in kg
height = 170 # in cm
print("Don't need to join the army")
gender = 'boy'
weight = 70 # in kg
height = 170 # in cm
print("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 = 7
print(70)
bottles = 11
print(100) # because 1 bottle is free
bottles = 23
print(210) # because 2 bottles are free
bottles = 20
print(190) # because you buy 19 bottles and gets 1 free
bottles = 21
print(200) # becuase you buy 20 bottles and gets 2 free, so one extra bottle
bottles = 22
print(200)
``` -->