You are on page 1of 48

ESSC/EESC 2030: Introduction to

Computational Earth System Science

Lec 04: Booleans, If-then-else Statement

1
Content of Today’s Lecture
- Booleans
- If-then-else Statement
- If, Else, Elif
- Boolean arrays and boolean indexing

2
Booleans

3
Booleans
- in human language, Yes or No, in Python, True or False.

Human Language On / Yes Off / No

Boolean in Python True False

Integer Representation 1 (or any number other 0


than 0 in Python)

4
Booleans
- Booleans are usually evaluated from an expression.
- e.g. the expressions 1 < 2 (Is 1 smaller than 2?) returns True,
while 2 + 2 == 5 (Is 2 plus 2 equals to 5?) returns False.
- Used for decision making.
- Testing, checking validity, and Test
- Flow control.
False

Ask Had lunch Lunch


yet?

True
Go back to
work
5
Common Tests in Earth Science
- Most common tests:
- Whether a number falls within a certain range of value.
- e.g. Is rainfall larger than 0.1 mm/hr?
- Compare the values of variables in different time/space.
- e.g. Is temperature today lower/higher than yesterday?

test rainfall <= 0.1mm/hr


False
rainfall data Rainfall > 0.1 ...
mm/hr

True
rainfall > 0.1mm/hr ...
6
Comparison Operators
Operation Meaning Conditions Results
(First assign
x = 3)
x = 3
< Strictly less than x < 5 True print(x < 5)
<= Less than or equal to x <= 3 True print(x <= 3)
print(x > 3)
> Strictly greater than x > 3 False
print(x >= -1)
>= Greater than or equal x >= -1 True print(x == 30)
to print(x != 2.5)
== (Double Equal to x == 30 False
Equal Sign)
!= Not equal to x != 2.5 True

7
Comparisons and Boolean
x = 3
Datatype Example
bool1 = x < 5
bool2 = x <= 3
Integer (9, -80, 0)
bool3 = x > 3
整數
bool4 = x >= -1
bool5 = x == 30
Float
bool6 = x != 2.5 (10.78, -1.0, 29.3)
(浮)點數

print(bool1, bool2, bool3) String ("Handsome Keung To",


print(bool4, bool5, bool6) 字串 "HK$ 1,000,000.00")

True True False Boolean


True False True (True, False)
布林值

8
Multiple Conditions
- In some cases, it involves more than one condition for a decision.
- Either all tests have to be satisfied.
- e.g. Input must be integer AND larger than zero
- Or only satisfy either one of the tests
- e.g. Issue temperature-related warning whenever
temperature is lower than 12°C OR higher than 33°C.
- In Python, we achieve this by the operators and/or.

False
Take MTR taller than or Aged 3 or
No ticket needed
95 cm? above?
True Buy ticket
9
Multiple Conditions

False
a variable integer and >0 …

True …

False
temp < = 12°C or >= 33°C No Action

True Weather Warning

10
Truth Table for and
● and : True if both are True

P Q P and Q

True True True

True False False

False True False

False False False

11
Truth Table for or
● or : True if at least one are true

P Q P or Q

True True True

True False True

False True True

False False False

12
Truth Table for xor
● xor : True if only one of them is true

P Q P xor Q

True True False

True False True

False True True

False False False

13
Truth Table for not
● not : Reverse the boolean value

P not P

True False

False True

14
Truth Table → A B and or not B xor
0 is False
Two Conditions 1 is True
0

0
0

1
0

0
0

1
1

0
0

1
Case Example Results 1 0 0 1 1 1
(First assign x = 3, y = 4)
1 1 1 1 0 0
True and True x < 5 and y <= 4 True

True and False x <= 3.5 and y > 6 False x = 3


y = 4
False and False x > 3 and y == 1 False
print(x < 5 and y <= 4)
print(x <= 3.5 and y > 6)
True or True x >= -1 or y < 8 True
print(x > 3 and y == 1)
print(x >= -1 or y < 8)
True or False x == 3 or y > 4 True
print(x == 3 or y > 4)
False or False x != 3 or y >= 5 False print(x != 3 or y >= 5)

15
Two Conditions
x = 3 x = 3
y = 4 y = 4
bool1 = x < 5 and y <= 4 bool1 = x <= 3
bool2 = x <= 3.5 and y > 6 bool2 = y == 1
bool3 = x > 3 and y == 1 bool3 = bool1 and bool2
Boolean as a datatype
bool4 = x >= -1 or y < 8 print(bool1)
bool5 = x == 3 or y > 4 print(bool2)
bool6 = x != 3 or y >= 5 print(bool3)
print(bool1, bool2, bool3)
print(bool4, bool5, bool6) True A boolean variable is
False either True or False
True False False False
True True False

16
Truth Table → A B and or not B xor
0 is False
1 is True
Chained Conditions 0

0
0

1
0

0
0

1
1

0
0

- How about three or more conditions? 1 0 0 1 1 1

- Rules: 1 1 1 1 0 0

- Bracket has the highest priority


- and has a higher priority than or
- The evaluation then follows the written sequence

Case Interpretation Results


True or True and False True or (True and False) True

(True or True) and False (True or True) and False False


→ True and False
True or True and False and True or (True and False) and True True
True → True or (False and True)
17
Exercise 1
- Without running codes, determine True/False for the following expressions.
Show your steps.
- True
- True or False
- True and False
- True and False or True
- True and (False or True)
- (False and True) or False
- (True or False) and (False and True) or False

18
Exercise 2
- Without running codes, determine True/False results for the following inputs
and conditions. Show your steps. The first one is done as an example.

Input(s) Condition(s) Result

age = 4 age >= 4 and age < 12 True and True -> True

age = 12 age >= 4 and age < 12

TT = 7.7 TT <= 12.0 or TT>=33.0

TC = True, wspd = 63 TC == True and (wspd >= 41 and wspd < 63)

TC = False, wspd = 41 TC != True or wspd >= 41

PGA = 200 PGA>=0 and PGA>=25 and PGA < 80


19
Flow Control

20
Flow Control : if… then… else
Example : work routine

Ask : Had lunch yet?


Yes → Go back to work
No → Lunch
Work

Example : work routine


Test
Ask False Ask : Had lunch yet?
Had lunch Lunch
yet?
Yes → Go back to work
Work No → Lunch
Work
True Go back to work
21
Flow Control
- Flow control is to interrupt and selectively execute certain statements of the
code.
- Common types:
- Selectional: Executes only when conditions are (not) met, i.e. conditional statement.
- Iterative: Executes the same statements for multiples time, i.e. loops. (Next Lecture)
- Application in Earth Science:
- Conditional statement: Data selection.
- Loops: Loop the same block as time/space propagates. (Next Lecture)
Test
False
Rainfall 1 Rainfall > No Signal
value 30mm/hr

True Amber Rainstorm Signal 22


Test
False
Rainfall Rainfall >

If Statement value 30mm/hr

True Amber Rainstorm


- In the form of “if <condition>:” Signal
- Executes the indented code below if condition is satisfied
(Boolean value of the condition is True).
- In other words, ignore the indented code if it is False.
- Continue to execute the remaining unindented code,
regardless if the condition is True or False.

Condition(s) False
< if … : >
...

True Executed code


when condition(s)
meet
23
If Statement

x = 5 #guessing the value of x

If statement: Declare your


if x == 7:
condition here. (x == 7)
Indented lines after print("Your guess is right")
if ____:
To be execute if the print("Your guess is x =",x)
condition returns True.
Your guess is x = 5
Unindented lines: Always executes

24
Ureply Quiz
If Statement https://ureply.mobi/

- Flow Chart of the codes in last page:

1 x = 5 #guessing the value of x


2
True
if x==7: 3 if x == 7:
4 print("Your guess is right")
5
print("Your guess 6 print("Your guess is x =",x)
is right") False
Your guess is x = 5

Q : if x is not equal to 7, which line is


print("Your guess skipping here?
is x =",x) A. 2 B. 3 C. 4 D. 5
25
< else: >
False Executed code
Condition(s)
< if … : >
when condition(s) ...
Else Statement is/are not meet

True Executed code


when condition(s)
meet

x = 5 #guessing the value of x

if x == 7:
Else statement: print("Your guess is right")
Placed at the same
indentation level with the else:
Indented lines after else:
if statement. print("Your guess is wrong")
To be execute if the condition
returns False.
print("Your guess is x =",x)

Your guess is wrong


Your guess is x = 5

26
Else Statement
- Flow Chart of the codes in last page: x = 5 #guessing the value of x

if x == 7:
True print("Your guess is right")
if x==7: else:
print("Your guess is wrong")
False
print("Your guess else:
print("Your guess is x =",x)
is right") print("Your guess
is wrong") Your guess is wrong
Your guess is x = 5

print("Your guess
is x =",x)
27
Ureply Quiz
Else Statement https://ureply.mobi/

Q : change x to 7, output = ? x = 5 #guessing the value of x

if x == 7:
A. Your guess is right print("Your guess is right")
else:
Your guess is x = 7
print("Your guess is wrong")
B. Your guess is wrong
Your guess is x = 7 print("Your guess is x =",x)

C. Your guess is x = 7
D. Your guess is x = 5

28
Floating-point Error and If Statement
- If statement involving comparison between floats can lead to unexpected results

Truncation here!
a = 0.1
b = 0.2
0.310 0.01001100110011001101…2
c = 0.3
print(a+b)
0.30000019…10 0.010011001100110011012
if a + b == c:
print("they are equal")
else: e.g. 0.3 = 2-2 + 2-5+ 2-6+ 2-9+ 2-10+ …
print("they are not the same") In binary, 0.010011001100...

0.30000000000000004
they are not the same
29
Floating-point Error : Solution (1)
- Solution: Define a tolerance for error:
if (c - 1e-6) < a + b < (c + 1e-6): if abs(a + b - c) < 1e-6:
# chained comparison print("they are equal")
print("they are equal") else:
else: print("they are not the same")
print("they are not the same")
they are equal
they are equal

c
c-(1e-6) c+(1e-6) (a+b) c

a+b 30
Floating-point Error : Solution (2)
- Solution: Solve “manually”
print(20.1/3) 6.7
print(20.1//3) 6.0
print(20.1%3) # Floating-point error here! 2.1000000000000014
print('%.2f' % (20.1%3)) # only print 2 decimal places 2.10
print(round(20.1%3,2)) # trucation here! 2.1
print(round(20.1%3,5)) # trucation here! 2.1

- the remainder of 20.1 divided by 3 is 2.1


- rounding 2.100000… to 2 decimal places is 2.10, it only shows 2.1 here
- rounding 2.100000… to 5 decimal places is 2.10000, it only shows 2.1 here

31
Ureply Quiz
Floating-point Error : Solution (2) https://ureply.mobi/

a = 0.1 Q : What is the value of a+b in python?


b = 0.2
c = 0.3

A. 0.03
if round(a+b,2) == c:
print("they are equal") B. 0.3
else:
C. 0.30000000000000004
print("they are not the same")
D. 0.30000000000000000
they are equal

32
7
0 5 9 14
Elif Statement
x = float(input("Please enter your guess"))
#allow user input of guess
When an if/elif
condition is met,
Elif statement: if x == 7: indented code directly
placed at the same below is executed.
print("Your guess is right")
indentation level elif/else
with the if elif 5 <= x <= 9:
statements thereafter
statement print("Your guess is close to the answer") are skipped (Exit).
elif x <= 0 or x >= 14:
5 <= x <= 9 print("Your guess is far from the answer")
is a chained
comparison. else:
print("Your guess is wrong")

print("Your guess is x =",x)


33
If-then-else Statement - Remarks
- elif and else are both optional.
- An arbitrary number of elif can be used.
- But else can be used only once as a catch-all.

34
Elif Statement
- Flow Chart of the script in the last page:
False False print
if x == 7 : elif 5 <= x <= 9: ... "Your guess is
x =",x
True True
print "Your print
guess is "Your guess is close
right!" to the answer"

The subsequent elif/else statements are skipped


if the current checking is satisfied. 35
Nested If-then-else Statement
x = float(input("Please enter your guess"))
#allow user input of guess

if x == 7:
print("Your guess is right")
elif 5 <= x <= 9:
print("Your guess is close to the answer")
elif x <= 0 or x >= 14:
It is possible to have a nested
print("Your guess is far from the answer")
if-elif-else statement inside
if x <= 0:
another one.
print("Hint: it is a positive number") Indentation level increases by one
else: for each nested if.
print("Your guess is wrong")

print("Your guess is x =",x)


36
Exercise 3
The Central Weather Bureau Seismic Intensity Scale is calculated from the Peak
Ground Acceleration (PGA, km s-2) and Peak Ground Velocity (PGV, km s-1)
following the rules below:

1. If PGA < 80km s-2, then the intensity is calculated from PGA according to the
following table:
Intensity 0 1 2 3 4

PGA range <0.8 0.8 ≤ PGA < 2.5 2.5 ≤ PGA < 8.0 8.0 ≤ PGA < 25 25 ≤ PGA < 80

2. If PGA ≥80km s-2, then the intensity is calculated from PGV according to the
following table:
Intensity 4 5- 5+ 6- 6+ 7

PGV range <15 15 ≤ PGV < 30 30 ≤ PGV < 50 50 ≤ PGV < 80 80 ≤ PGV < 140 ≥140 37
Exercise 3
Write a script to calculates and prints the Central Weather Bureau Seismic Intensity
according to the PGA (in km s-2) and PGV(in km s-1) input by the user.

The script should be able to handle improper numerical inputs - upon receiving
improper numerical inputs, print a message to notify the user.

See the next slide for sample inputs and sample outputs.

38
Exercise 3
Sample inputs and outputs:

Inputs Outputs

PGA : 10 Earthquake Intensity: 3


PGV : 100

PGA : 100 Earthquake Intensity: 4


PGV : 10

PGA : 100 Earthquake Intensity: 6+


PGV : 100

PGA : 100 Invalid input: PGA and PGV should be non-negative.


PGV : -10
39
Boolean Arrays
- Comparison operators are also applicable for arrays which return the boolean
values either against a single value or element-wise.
import numpy as np

temp1 = np.array([25, 26.1, 27.5, 24.9, 26.1, 27.5, 25.6, 25.9, 25.9, 27.1])
temp2 = np.array([27, 24.9, 28.5, 25.3, 25.5, 26.7, 29.9, 26.4, 25.8, 27.2])
ref_temp = 26
print(temp1 < temp2) #element-wise comparison between two arrays
print(temp1 > ref_temp) #comparison of an array against a single value

[ True False True True False False True True False True]
[False True True False True True False False False True]

40
Truth Table → A B and or not B xor
0 is False 0 0 0 0 1 0
1 is True
Boolean Arrays 0
1
1
0
0
0
1
1
0
1
1
1
1 1 1 1 0 0
- The newly returned boolean arrays can be compared element-wise using the
function numpy.logical_and() and numpy.logical_or() (& and |)
- Note: Chained comparison does not work for arrays
import numpy as np

temp1 = np.array([25, 26.1, 27.5, 24.9, 26.1, 27.5, 25.6, 25.9, 25.9, 27.1])
temp2 = np.array([27, 24.9, 28.5, 25.3, 25.5, 26.7, 29.9, 26.4, 25.8, 27.2])
ref_temp = 26
print(temp1 < temp2) #element-wise comparison between two arrays
print(temp1 > ref_temp) #comparison of an array against a single value
print(np.logical_and(temp1 < temp2, temp1 > ref_temp)) # What are the results?

[ True False True True False False True True False True]
[False True True False True True False False False True]
[ False False False False False True]
41
Boolean Indexing
import numpy as np [5 6 4]

arr1 = np.array([1, 3, 5, 6, 2, 4])


mask = np.array([False, False, True, True, False, True])
arr2 = arr1[mask]
print(arr2)

1 3 5 6 2 4

False False True True False True

5 6 4

42
Ureply Quiz
Boolean Indexing https://ureply.mobi/

import numpy as np [5 6 4]

arr1 = np.array([1, 3, 5, 6, 2, 4])


mask = arr1 > 3
arr2 = arr1[mask]
print(arr2)

? (box1) 1 3 5 6 2 4

? (box2) False False True True False True

? (box3) 5 6 4 Q : Which variables are in box1, box2 and box3?

43
Boolean Indexing
import numpy as np [5 6 4]
[5 6 4]
[1 3 2]
arr1 = np.array([1, 3, 5, 6, 2, 4])
#Part A
mask = np.array([False, False, True, True, False, True])
print(arr1[mask]) #[5 6 4]
#Part B
mask = arr1 > 3 #[False False True True False True]
print(arr1[mask]) #[5 6 4]
print(arr1[~mask]) #[1 3 2]

● Part A and Part B give the same results [5 6 4]. Why?


● What does ~ mean in [~mask]?

44
Truth Table → A B and or not B xor
0 is False 0 0 0 0 1 0
1 is True
Boolean Indexing 0
1
1
0
0
0
1
1
0
1
1
1
1 1 1 1 0 0
import numpy as np
arr1 = np.array([1, 3, 5, 6, 2, 4])
#Part A
mask = np.logical_or(arr1 > 3, arr1 == 1)
print(arr1[mask]) #[1 5 6 4]

#Part B
print(arr1[np.logical_or(arr1 > 3, arr1 == 1)]) #[1 5 6 4]

● Part A and Part B give the same results [1 5 6 4]. Why?

45
Exercise 4
Given a NumPy array of [2 4 6 8 1 3 5 7].

● Without defining a new array, output (print) the followings by boolean indexing
with comparison operators (use “mask”):
○ [6 8 7]
○ [2 4 1 3 5]
○ [4 6 3 5]
○ [2 4 6 8 1 3 5 7]
○ [2 4 6 8]

46
Extended Readings
- W3Schools: Python Booleans
https://www.w3schools.com/python/python_booleans.asp
- W3Schools: Python Operators
https://www.w3schools.com/python/python_operators.asp
- Python Documentation: Operator Precedence
https://docs.python.org/3/reference/expressions.html#operator-precedence
- W3Schools: Python If…Else
https://www.w3schools.com/python/python_conditions.asp
- Boolean NumPy Array (MTH337, Univeristy at Buffalo)
http://www.math.buffalo.edu/~badzioch/MTH337/PT/PT-boolean_numpy_ar
rays/PT-boolean_numpy_arrays.html
47
For “late add” students (Added in Week 2/3)
You are required to complete and submit all previous homework.

Please follow the due time below.

You should also notify the Instructors and the TAs about your late participation.

You may lose the corresponding marks if you fail to do so.

Homework 1, 2 Homework 3
Due time: Due time:
10th Feb 23:59 7th Feb 23:59

48

You might also like