0% found this document useful (0 votes)
1 views36 pages

Lecture 3 Iterations Functions

Uploaded by

11Kk112233
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views36 pages

Lecture 3 Iterations Functions

Uploaded by

11Kk112233
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

SEE1002

Introduction to Computing for Energy and Environment

Lecture 3: Iterations and functions


Canvas→Assignments→Assignment1

Assignment 1
If you were given a robot that looked just like you
(hyper-realistic) as a gift from Santa, so you will send
a robot to the CityU campus from your home to take
courses and do campus life.

Please use “if”, “for”, “while”, “break”, and “pass”


commands at least once for each command, and
write down python code for doing your campus life
instead of you.

It should start from your home (preparing for daily


life) and include going to campus (by MTR or buses or
walking), finding classrooms, talking naturally with
Hint: Practical Lab 3 (python gaming) your classmates, and have lunch, and so on.

Amount: more than 1 Page of A4 (file format: PDF),


Rule: you need to include all of “if”, “for”, “while”, “break”, and “pass” statements
Due: 13 Feb (11:59 pm)
For vs While
>>> i = 1 >>> for i in range(1,11):
>>> while i<11: ... print(i)
... print(i) ...
... i+=1 1
... 2
1 3
2 4
3 5
4 6
5 7
6 8
7 9
8 10
9
10
The for loop is more compact!
For vs While
>>> value=32.0 >>> value=32.0
>>> while value>2.0: >>> for i in range(4):
... value/=2.0 ... value/=2.0
... print('current ... print('current value=',value)
value=',value) ...
... else: current value= 16.0
... print('final value=',value) current value= 8.0
... current value= 4.0
current value= 16.0 current value= 2.0
current value= 8.0 >>> print('final value=',value)
current value= 4.0 final value= 2.0
current value= 2.0
final value= 2.0
The while loop is more useful when we don’t know
how many times the loop will be executed.
For vs While
Structure of for statement
Use of else

>>> for i in range(3): >>> for i in range(3): >>> for i in range(3):


... print(i) ... print(i) ... print(i)
... ... else: ... else:
0 ... print("we're done") ... print("we're done")
1 ... ...
2 0 0
>>> print("we're done") 1 1
we're done 2 2
we're done we're done
>>> print("we're done")
we're done
iteration

for i in range(len(t_list)):
if t_list[i]>=33: A for statement needs to have a range for iteration
n_hotday[m_list[i]-1]+=1
(from Lecture 2)

An iteration does not need to have range!


(from Practical Lab 4)
iteration
MTR=['KowloonTong','Admiralty','SouthHorizons','TsimShaTsui’]
>>> for i in range(len(MTR)):
... print(MTR[i])
...
KowloonTong >>> for stations in MTR: Do not need to specify size of list
Admiralty ... print(stations) (iteration range)
SouthHorizons ...
TsimShaTsui KowloonTong
Admiralty
SouthHorizons
TsimShaTsui

>>> for x in MTR:


... print(x)
...
KowloonTong
Admiralty
SouthHorizons
TsimShaTsui
Iterating over multiple lists
>>> year=[1982,1980,2016,1979]
>>> for i,stations in enumerate(MTR):
... print(stations,year[i])
...
KowloonTong 1982
Admiralty 1980 >>> for stations,years in zip(MTR,year):
SouthHorizons 2016 ... print(stations,years)
TsimShaTsui 1979 ...
KowloonTong 1982
Admiralty 1980
SouthHorizons 2016
TsimShaTsui 1979
Nested loops
>>> for i in range(10): >>> for i in range(3):
... print('i=',i) ... for j in range(3):
... ... print('i=',i,'j=',j)
i= 0 ...
i= 1 i= 0 j= 0
i= 2 i= 0 j= 1 Changing j first
i= 3 i= 0 j= 2
i= 4 i= 1 j= 0
i= 5 i= 1 j= 1
i= 6 i= 1 j= 2
i= 7 i= 2 j= 0
i= 8 i= 2 j= 1
i= 9 i= 2 j= 2
We’ll apply this to the case of
day, month, year…
Break & Continue
>>> for i in range(10): >>> i=0
... if i==4: >>> while i<=3:
... break ... print(i)
... else: ... i+=1
... print(i) ...
... 0
0 1
1 2
2 >>> for i in range(10): 3
3 ... if i>3:
... continue
... else:
... print(i)
...
0
1
2
3
Pass
>>> for i in range(10):
... if i==7:
... print(Lucky Seven i=%d' %(i))
... else:
... pass
...
Lucky Seven i=7
function
A function is analogous to the formula function of a calculator or a mathematical function.

x → f(x)
x,y → g(x,y)
Repeating these instructions explicitly
makes the code longer than necessary.
The objective of the function (code reuse) is
to avoid repeating instructions again and
again.
function
>>> def circle(x): >>> def hotd(x):
... area=x*x*3.141592 ... nd = len([y for y in t_list if y>=33.0])
... return area ... return nd
... ...
>>> print(circle(2)) >>> t_list = range(0,40)
12.566368 >>> hotd(t_list)
>>> print(circle(5)) 7
78.5398
>>> def cold(x):
>>> def circle2(x): ... nd = len([y for y in t_list if y<=12.0])
... x=x*x*3.141592 ... return nd
... return x ...
... >>> cold(t_list)
>>> print(circle2(2)) 13
12.566368
>>> print(circle2(5))
78.5398
function
import random

def get_random_number():
num = []
while len(num)<=6:
r_num = random.randint(1, 49)
if r_num not in num:
num.append(r_num)
num.sort()
return num

get_random_number()
Please be careful when you copy and paste!

function ' ‘
def temp24(x):
import urllib
filen='temp24.csv'
urllib.request.urlretrieve('https://data.weather.gov.hk/weatherAPI/hko_data/regional-
weather/latest_past24_temperature_diff.csv', filen)
f = open(filen,'r',encoding='utf-8')
lines = f.readlines()
station_list=list()
temp_list=list()
for line in lines:
Chek Lap Kok -3.1
info = line.split(',') Cheung Chau 9.4
time = list(info[0])
temp = list(info[2])
Clear Water Bay 9.0
if time[0]=='2': Happy Valley -2.8
if temp[0]!='N':
year=(''.join(time[0:4])) 'Year:2023,Month:01,Day:25,Hour:09,Minuate:50'
month=(''.join(time[4:6]))
day=(''.join(time[6:8]))
hour=(''.join(time[8:10]))
minuate=(''.join(time[10:12]))
str_time= "Year:{},Month:{},Day:{},Hour:{},Minuate:{}".format(year,month,day,hour,minuate)
station_list.append(info[1])
temp_list.append(float(info[2]))
for i in range(len(station_list)):
if abs(temp_list[i])>=x:
print(station_list[i],temp_list[i])
return str_time

temp24(2.0)
Earth’s energy budget https://youtu.be/82jE-yvB8xU
Solar constant (S0)
is a flux density measuring mean solar electromagnetic radiation (solar irradiance) per unit area. It is measured on a surface
perpendicular to the rays, one astronomical unit (AU) from the Sun (roughly the distance from the Sun to the Earth).

• Total radiation emitted by the sun can be calculated by


using the Stefan-Boltzmann equation
" #
E! = εσT! & 4πR !
• σ = 5.670373 × 10!" W m!# K !$
• T% = 5778 K
• R % = 6.9634 × 10" m
• E% = ?
Solar constant (S0)
import numpy
import numpy as np
from numpy import sqrt
sigma = 5.67e-08
Ts = 5778
Rs = 6.9634e+08
Re = 1.49597870e+11
pi = 3.141592
Es = sigma * Ts**4 * 4 * pi * Rs**2
print(Es)
3.850753057423705e+26
Solar constant (S0)
#
E! = 4πR " & S$
E!
S$ =
4πR " #
Re = 1.495978707×1011 m (1 Astronomical Unit; AU)

S0 = Es/(4*pi*Re**2)
print(S0)

http://www.schoolphysics.co.uk/age16-

%#
19/Astrophysics/text/Solar_energy/index.html

S$ = 1369.26 W m
Radiative equilibrium temperature (Te)

Energy In = S& 1370 W m!# 5 Area


The Earth’s shadow area is a circle (not a sphere)

Parallel solar radiation


Day Night

R&

"
πR !
The Earth’s shadow area is a circle (not a sphere)

Parallel solar radiation The mid-latitude and Arctic have


less solar radiance per unit area

R&

"
πR ! Equator
Mid-latitude
The Earth’s shadow area is a circle (not a sphere)

'!
S& = 1370 W m!#
R&

"
πR !

#
= S$ & πR %
The Earth’s shadow area is a circle (not a sphere)

Energy In = S& 1370 W m!# 5 Area(πR (#) 5 ⋯ (9:;<=>? )

e do
Alb
Albedo (the proportion of light reflected from a surface)
!~0.3
Energy In = S& 1370 W m!# 5 Area(πR (#) 5 (1 − B)
(70%)

0 %)
e d o (3
Alb
Radiative equilibrium temperature (Te)
Stefan–Boltzmann law

σT" # + 4πR " $ IN OUT


# " #
S! + πR " $ S$ & πR & & (1 − 5) = σT& & 4πR &
Energy receiving area Energy outgoing area

e do
Al b

Stefan–Boltzmann law

Re: the radius of Earth


σ: Stefan-Boltzmann constant
Te: radiative equilibrium temperature
Radiative equilibrium temperature (Te)
Stefan–Boltzmann law

σT" # + 4πR " $ IN OUT


# " #
S! + πR " # S$ & πR & & (1 − 5) = σT& & 4πR &
Energy receiving area Energy outgoing area

e do
Al b

Stefan–Boltzmann law ! S$
T& = (1 − 5)
Re: the radius of Earth 4σ
σ: Stefan-Boltzmann constant
Te: radiative equilibrium temperature
Radiative equilibrium temperature (Te)
Stefan–Boltzmann law

σT" $ + 4πR " # IN OUT


# " #
S! + πR " # S$ & πR & & (1 − 5) = σT& & 4πR &
Energy receiving area Energy outgoing area

e do
Al b

S! = 1369.26 W m"#
Stefan–Boltzmann law ! S$
T& = (1 − 5)
Re: the radius of Earth 4σ 1~0.3

σ: Stefan-Boltzmann constant
σ = 5.670373 × 10"$ W m"# K "%
Te: radiative equilibrium temperature
Radiative equilibrium temperature (Te)
import numpy
from numpy import sqrt
sigma = 5.67e-08
Ts = 5778
Rs = 6.9634e+08
Re = 1.49597870e+11 #1AU
pi = 3.141592
Es = sigma * Ts**4 * 4 * pi * Rs**2
S0 = Es/(4*pi*Re**2)
albedo = 0.3
T = sqrt(sqrt(S0/(4*sigma)*(1-albedo)))-273.16
Radiative equilibrium temperature (Te)
Radiative equilibrium temperature (Te)
Radiative equilibrium temperature (Te)
planet=['Mercury','Venus','Earth','Mars','Jupiter','Saturn','Uranus','Nep
tune']
AU=[0.387,0.722,1.0,1.52,5.2,9.58,19.2,30.1]
albedo=[0.119,0.9,0.306,0.25,0.343,0.342,0.30,0.29]
T = list(map(Planet_T,AU,albedo))
for i in range(0,len(planet)):
print('planet=%s, Te=%.2f' %(planet[i],T[i]))

def Planet_T(AU,albedo): planet=Mercury, Te=160.95


planet=Venus, Te=-88.68
planet=Earth, Te=-18.74
planet=Mars, Te=-62.76
planet=Jupiter, Te=-163.11
planet=Saturn, Te=-192.05
planet=Uranus, Te=-214.97
planet=Neptune, Te=-226.52
Radiative equilibrium temperature (Te)
AU=[1 for i in range(10)] Fix the distance from Sun to 1 AU as the Earth
import numpy as np
albedo = np.arange(0,1,0.1)
T = list(map(Planet_T,AU,albedo))
print('Min T=%.2f, Max T=%.2f' %(min(T),max(T)))

Have you heard about geoengineering?


Min T=-116.41, Max T=5.59

planet=Earth, Te=-18.74
Radiative equilibrium temperature (Te)
planet=Earth, Te=-18.74°C

Actually, observed surface temperature is ~14°C


(32.5°C warmer than Te)

Greenhouse
effect

You might also like