By doing this exercise you will apply Python basics that we learned today: loops, lists, functions, strings. In addition, you will try to write data to a text file.
The bulk formula for the sea-to-air heat flux is
$Q = \rho c_p C_H (u_{atm} - u_{sea}) (T_{sea} - T_{atm}) $
where
1. Create data of within the following range
Hint: use range()
function and wrap it in a list()
function.
If you want to create lists of arbitrary values (e.g. non-integer), use my_list = [ ]
notation.
In [1]:
## Your code
wind_speed = list(range(0,20,2))
sst = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Print out the wind_speed
and sst
variables to check yourself.
In [2]:
print(wind_speed)
sst
Out[2]:
2. Create a function to calculate the heat flux
return
statement to return the outputYou've already forgotten it, but the formula is $Q = \rho c_p C_H (u_{atm} - u_{sea}) (T_{sea} - T_{atm}) $
In [3]:
def calc_heat_flux(u_atm, t_sea, rho=1.2, c_p=1004.5, c_h=1.2e-3, u_sea=1, t_atm=17):
q = rho * c_p * c_h * (u_atm - u_sea) * (t_sea - t_atm)
return q
3. In a loop, calculate the heat flux with wind speed and temperature as inputs
heat_flux
of $Q$ valuesheat_flux
list
In [4]:
heat_flux = []
for u, t in zip(wind_speed, sst):
q = calc_heat_flux(u, t)
heat_flux.append(q)
Print out heat_flux
variable to check that the values are sensible (no pun intended).
In [5]:
heat_flux
Out[5]:
4. Open a new text file for writing
Now, you need to open a file. Explore the built-in function open()
:
In [6]:
# open?
The recommended way of writing/reading files is using the context statement with
:
# example
with open('super_descriptive_file_name', mode='r') as your_file:
your_file.read()
5. Loop over the function output and write the data to the file
heat_flux_data.txt
for writingwith
statementwith
code block, write a loop to iterate through the heat_flux
values and write each of them on a new lineread()
as in the example above, use write()
methodwrite()
method needs string type inputstr()
function or, even better, format()
method
In [7]:
# with open('heat_flux_data.txt', 'w') as f:
# for h in heat_flux:
# f.write('{:3.1f}\n'.format(h))
Use a text editor of your choice (or Jupyter!) to check the contents of the file.
In [8]:
# !cat heat_flux_data.txt