ESSC/EESC 2030: Introduction To Computational Earth System Science
ESSC/EESC 2030: Introduction To Computational Earth System Science
ESSC/EESC 2030: Introduction To Computational Earth System Science
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.
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
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?
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)
(浮)點數
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
10
Truth Table for and
● and : True if both are True
P Q P and Q
11
Truth Table for or
● or : True if at least one are true
P Q P or Q
12
Truth Table for xor
● xor : True if only one of them is true
P Q P xor Q
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
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
- Rules: 1 1 1 1 0 0
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.
age = 4 age >= 4 and age < 12 True and True -> True
TC = True, wspd = 63 TC == True and (wspd >= 41 and wspd < 63)
20
Flow Control : if… then… else
Example : work routine
Condition(s) False
< if … : >
...
24
Ureply Quiz
If Statement https://ureply.mobi/
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)
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/
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
31
Ureply Quiz
Floating-point Error : Solution (2) https://ureply.mobi/
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")
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"
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")
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
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]
1 3 5 6 2 4
5 6 4
42
Ureply Quiz
Boolean Indexing https://ureply.mobi/
import numpy as np [5 6 4]
? (box1) 1 3 5 6 2 4
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]
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]
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.
You should also notify the Instructors and the TAs about your late participation.
Homework 1, 2 Homework 3
Due time: Due time:
10th Feb 23:59 7th Feb 23:59
48