SEE1002
Introduction to Computing for Energy and Environment
Lecture 2: Basic programming Languages/Grammars
Basics: Logical operators
>>> weekday=True
>>> weekend=False
>>> not weekday
False
>>> not weekend
True
>>> weekday and weekend
False
>>> weekday or weekend
True
Basics: Logical operators
A B A and B A B A or B
False False False False False False
False True False False True True
True False False True False True
True True True True True True
Basics: Program flow
Make
thin
dough
Wrap up
Linear flow with
or ingredient
Sequential flow
Steam
and
enjoy!
Basics: Program flow
>>> x1=input('Enter x1: ') >>> x1=int(input('Enter x1: '))
Enter x1: 2 Enter x1: 2
>>> x2=input('Enter x2: ') >>> x2=int(input('Enter x2: '))
Enter x2: 4 Enter x2: 4
>>> x2=x1+x2 >>> x2=x1+x2
>>> x2 >>> x2
'24' 6
Basics: Program flow
>>> x1=int(input('Enter x1: ')) >>> x1=int(input('Enter x1: '))
Enter x1: 2 Enter x1: 2
>>> x2=int(input('Enter x2: ')) >>> x2=int(input('Enter x2: '))
Enter x2: 4 Enter x2: 4
>>> x2=x1+x2 >>> x2
>>> x2 4
6 >>> x2=x1+x2
Different result
(Sequence is important!)
Basics: Branching
If “Month” is equal to the target month,
IF and
If Max temperature is above 33℃
branch
branch In case you want to have a summation of hot & cold days,
If “Month” is equal to the target month,
and
(If Max temperature is above 33℃
or
If Min temperature is below 12℃)
Basics: Branching
>>> x=34 >>> x=12
>>> if x>33: print("Hot day!")
>>> if x>33: print('Hot day!’) ...
... >>>
Hot day!
The basic structure of the “if” statement:
if [condition]: [command]
>>> IF x>33: print("Hot day!")
File "<stdin>", line 1
IF x>33: print("Hot day!")
^
SyntaxError: invalid syntax
Basics: Branching
>>> x=34
>>> if x>33: print('Hot day!')
... else: print('Not hot day')
...
Hot day!
>>> x=33
>>> if x>33: print('Hot day!')
... else: print('Not hot day')
...
Not hot day
Basics: Branching
x=11
>>> if x>33: print('Hot day!')
... else:
... if x<12: print('Cold day')
... else: print('Normal day')
...
Cold day
elif:
It can be thought of as “else if”, i.e., code to be
>>> if x>33: print('Hot day') executed if another condition is satisfied.
... elif x<12: print('Cold day')
This code is shorter and easy to read.
... else: print('Normal day') The risk of error is reduced
... as compared to a longer one.
Cold day
Basics: Branching
If “Month” is equal to the target month,
and
If Max temperature is above 33℃
If “Month” is equal to the target month,
and
(If Max temperature is above 33℃
or
If Min temperature is below 12℃)
Basics: Branching
>>> y=True
>>> type(y)
<class 'bool’>
>>> if y==True: print('y is True')
... else: print('y is False')
...
y is True
Basics: Branching
Operator Condition
< Less Than
> Greater Than
<= Less Than or Equal to
>= Greater Than or Equal to
== Equal to
!= Not Equal to
Basics: Branching
>>> a=330
>>> b=330
>>> print("A") if a > b else print("=") if a == b else print("B")
=
>>> a=200
>>> b=33
>>> c=500
>>> if a>b and c>a: print("Both conditions are True")
...
Both conditions are True
>>> if a>b or a>c: print("At least one of the conditions is True")
...
At least one of the conditions is True
>>> if b>a: pass
...
Just passed
QUIZ
Print "Hello World" if a is greater than b.
a = 50
b = 10
Q1 a Q2 b Q3
Print(“Hello World”)
Go to Canvas → Quizzes
→ Pop-up Quiz on Lecture2 (17 JAN)
Access code: kowloon
QUIZ
Using IF statement…
Basics: List & Loop
We can do calculations for every cases manually,
but is there any efficiency way to do at once?
We need to have data with array
and process with loops
Basics: List
list
>>>
data=[29.7,28.4,30.3,29.4,29.7,30.3,31.6,33.8,33.3,34.2,35.1
,36.2]
>>> data
[29.7, 28.4, 30.3, 29.4, 29.7, 30.3, 31.6, 33.8, 33.3, 34.2,
35.1, 36.2]
>>> data[0]
29.7
>>> data[11]
36.2
>>> data[12]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> data[10:12]
[35.1, 36.2]
Basics: List
>>> data[0]=29.6
>>> data[0]
29.6 Can change values in array
>>> data=(29.7,28.4,30.3,29.4,29.7,30.3,31.6,33.8,33.3,34.2,35.1,36.2)
>>> data[0]
29.7
>>> data[0]=29.6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Can not change values in array
Basics: List
Do not decide the size of the array at first.
>>> list=[]
>>> list.append(0)
>>> list.append(1)
>>> list.append(2)
>>> list
[0, 1, 2]
Basics: List Start & stop
range([start,]stop[,increment]) >>> a2=range(0,10)
>>> a2[0]
>>> a1=range(10) 0
>>> a1[0] >>> a2[1]
0 1
>>> a1[1] >>> a2[2]
1 2
>>> a1[10] >>> a2[3]
Traceback (most recent call last): 3
File "<stdin>", line 1, in <module>
IndexError: range object index out of range >>> a3=range(0,10,2)
>>> a1[9] >>> a3[0]
9 0
>>> a3[1]
Checking
2
length of array
Start is optional. By default, Start=0 >>> a3[2]
Increment is optional. By default, increment=1 integer 4
>>> len(a3)
5
Basics: List
Even number
>>> 6 in a3
True
Boolean
>>> 7 in a3
False Odd number
Dictionaries with braces {}
>>> MTR={'KowloonTong':1982,'Admiralty':1980,'SouthHorizons':2016}
>>> MTR
{'KowloonTong': 1982, 'Admiralty': 1980, 'SouthHorizons': 2016}
>>> MTR['KowloonTong']
1982
>>> MTR[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
Basics: List
>>> MTR.update({'TsimShaTsui':1979})
>>> MTR['TsimshaTsui']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'TsimshaTsui'
>>> MTR['TsimShaTsui']
1979
Basics: Loop
start, stop, increment
>>> for i in range(10,101,10):
... print( 'the sqrt of',i,' = ',float(i)**0.5)
...
the sqrt of 10 = 3.1622776601683795
the sqrt of 20 = 4.47213595499958
the sqrt of 30 = 5.477225575051661
the sqrt of 40 = 6.324555320336759
the sqrt of 50 = 7.0710678118654755
the sqrt of 60 = 7.745966692414834
the sqrt of 70 = 8.366600265340756
the sqrt of 80 = 8.94427190999916
the sqrt of 90 = 9.486832980505138
the sqrt of 100 = 10.0
Basics: Loop
Print only first 2 decimal places
>>> for i in range(10,101,10):
... print( 'the sqrt of %d = %.2f' %(i,float(i)**0.5))
...
the sqrt of 10 = 3.16
the sqrt of 20 = 4.47
the sqrt of 30 = 5.48
the sqrt of 40 = 6.32
the sqrt of 50 = 7.07
the sqrt of 60 = 7.75
the sqrt of 70 = 8.37
the sqrt of 80 = 8.94
the sqrt of 90 = 9.49
the sqrt of 100 = 10.00
Basics: Loop
>>> for i in range(12): >>> for i in range(12):
... print(data[i]) ... if data[i]>33:
... ... print(data[i])
29.7 ...
28.4 33.8
30.3 33.3
29.4 34.2
29.7 35.1
30.3 36.2 Can be replaced with
31.6 n_hotday +=1
33.8
33.3 >>> n_hotday = 0
34.2 >>> for i in range(len(data)):
35.1 ... if data[i]>33:
36.2 ... n_hotday = n_hotday+1
...
>>> n_hotday
5
Basics: Loop
while <expression>:
statement 1.1
[...] executed if expression==True
else:
statement 2.1
[...] executed if expression==False
Basics: Loop get money & serve coffee
Remain coffee is 9.
>>> coffee = 10
get money & serve coffee
>>> money = 300
Remain coffee is 8.
>>> while money:
get money & serve coffee
... print("get money & serve coffee")
Remain coffee is 7.
... coffee = coffee-1
get money & serve coffee
... print("Remain coffee is %d." % coffee)
Remain coffee is 6.
... if coffee==0:
get money & serve coffee
... print("coffee is over. stop serving.")
Remain coffee is 5.
... break
get money & serve coffee
...
Remain coffee is 4.
get money & serve coffee
Remain coffee is 3.
get money & serve coffee
Remain coffee is 2.
get money & serve coffee
Remain coffee is 1.
get money & serve coffee
Remain coffee is 0.
coffee is over. stop serving.
https://youtu.be/LrHTR22pIhw
Basics: Loop
Infinity loop (be careful!)
>>> while True:
... print("You need to type Ctrl+C for exit this while statement")
You need to type Ctrl+C for exit this while statement
You need to type Ctrl+C for exit this while statement
You need to type Ctrl+C for exit this while statement
You need to type Ctrl+C for exit this while statement
You need to type Ctrl+C for exit this while statement
You need to type Ctrl+C for exit this while statement
You need to type Ctrl+C for exit this while statement
^CYou need to type Ctrl+C for exit this while statement
Printing something also needs CPU and RAM resources!
Basics: Loop
>>> import csv
>>> f = open(‘location/CLMMAXT_HKO_2022.csv','r',encoding='utf-8')
>>> rdr=csv.reader(f)
>>> for line in rdr:
... print(line)
Basics: Loop
import csv
f = open('location/CLMMAXT_HKO_2022.csv','r',encoding='utf-8')
lines = f.readlines()
t_list=list()
m_list=list()
d_list=list()
for line in lines:
info = line.split(',')
if info[0]=='2022':
t_list.append(float(info[3]))
m_list.append(int(info[1]))
d_list.append(int(info[2]))
n_hotday = [0 for i in range(12)]
for i in range(len(t_list)):
if t_list[i]>=33:
n_hotday[m_list[i]-1]+=1
n_hotday
Good job!
Now, you have learned branch (if) & loop (for) statements.
You can be a programmer!
Let’s have fun programming in practical labs!
Big QUIZ #1 on 31/01/2023
You need to have a laptop or tablet or mobile phone
to take the quiz on the Canvas system.
If you don’t have those things,
contact the CityU library to borrow one.
Access code will be given in this lecture room. (LT-11)
Time for QUIZ: from 9 am to 10:30 am
Two TAs will be watching you.
Cheating will result in 0 points for this quiz.
Python gaming on 30/01/2023
Please make an account before 30/01/2023
https://codecombat.com/students?_cc=RightLeftName
You will get an email from this gaming platform
&
You need to verify (activate) your email account
After 1.5-hour python gaming,
You need to upload this page (home) by screensaver
(screenshot) with your name and progress
Due: 11 am, 30/01/2023
(You don’t need to reach certain level or progress…
Important thing is enjoying gaming in Python!)
Python gaming on 30/01/2023
Play 1.5 hours
&
Upload your final stage
(where you reached)
to Canvas!