Earth & Environmental Computing · Week 02 · Course session · 29 slides
Download HTML
Earth & Environmental Computing | Computational Methods for Earth & Environmental Science | 16-Week Course

Python Basics

Variables, lists, dictionaries, and f-strings, each attached to a physical quantity with a unit.

Variables · Lists · Dictionaries · F-strings · Units
Week 02·Course session·Open Course Materials | Adapt for your classroom·Week 2 | Course session
Learning Objectives

By the end of this lecture, you will be able to...

  • Create and name variables for scientific quantities
  • Choose between lists and dictionaries, and index both
  • Format output with f-strings and controlled precision
  • Explain why variable names should carry units
Contents

Today's Lecture

01Variables, types, and units
03Dictionaries: labelled data
02Lists: ordered data
04Putting it together
Recap

Last Week in Sixty Seconds

  • Reproducible = same data and same code give the same number, hands-free
  • The path cell finds the project root from wherever the notebook opens
  • Restart and Run All before every submission, all semester
  • Today: the Python those notebooks are written in
Motivation

Why Names and Units Matter

A famous failure

  • 1999: Mars Climate Orbiter lost
  • One team used newton-seconds, another pound-seconds
  • No error message, just a missing spacecraft

Your defense

  • temp_c, not x
  • elevation_ft, not elev2
  • Units in the name = errors visible at a glance
Data

Today's Datasets

FileSourceCoverageUsed for
iowa_city_weather_daily.csvIowa Environmental Mesonet, station IOWDaily, 2019–2025, 2,549 rowsTemperatures, wind, the station record
Station metadata, from the same fileStation IOW: 41.64 N, 91.54 W, 204 mOne row per day, constant columnsThe dictionary example
01

Variables, Types, and Units

A name that carries its unit is the cheapest error check you have.

01 · Variables, types, and units

Variables Are Named Values

Python

temp_c = -2.1                      # daily mean, deg C
temp_f = temp_c * 9 / 5 + 32       # unit conversion
station_id = "IOW"                 # text, not a number

print(temp_c, temp_f, station_id)
  • A good name states what and in which unit
  • Types differ: numbers compute, strings label
01 · Variables, types, and units

Types Decide What Operations Mean

Python

>>> 3 + 4
7
>>> "3" + "4"
'34'
>>> "elevation: " + 204.0
TypeError: can only concatenate str (not "float") to str
  • The same + does different work on different types
  • This TypeError will be the most common message this week
01 · Variables, types, and units

F-strings: Values into Sentences

f"Daily mean: {temp_c:.1f} deg C"

f"..." = formatted string literal

{temp_c} = insert the variable's value

:.1f = one decimal place, fixed point

deg C = the unit, written by you

  • Scientific communication in one line: value, precision, unit
Pause and think

?

Without the :.1f, Python prints -2.0991512345679015. Why is printing twelve decimals of a daily mean temperature scientifically misleading?

The thermometer never measured that precisely
Precision in print implies precision in knowledge
02

Lists: Ordered Data

Seven days of temperature, indexed from zero.

02 · Lists

Lists Hold Ordered Data

Python

week_temps = [-2.1, -4.9, -1.3, 0.8, 2.4, 1.1, -0.6]

week_temps[0]      # -2.1   first item
week_temps[-1]     # -0.6   last item
week_temps[1:4]    # [-4.9, -1.3, 0.8]   three items, not four
  • Counting starts at zero
  • A slice [1:4] stops BEFORE index 4
02 · Lists

Lists Come with Built-in Tools

  • sum(week_temps) adds everything
  • len(week_temps) counts items
  • max(week_temps), min(week_temps) find extremes
  • sum / len = a mean you computed yourself
02 · Lists

Two Routes to One Number

01

Given

Seven daily mean temperatures from the first week of the record.

02

Solve

Route 1: sum(temps) / len(temps). Route 2: pandas .mean() on the same column.

03

Interpret

Both give the same value. Two independent routes agreeing is your first correctness test.

03

Dictionaries: Labelled Data

One station, asked by name rather than by position.

03 · Dictionaries

Dictionaries Hold Labeled Data

Python

station = {
    "id": "IOW",
    "latitude": 41.64,
    "longitude": -91.54,
    "elevation_m": 204.0,
}

station["elevation_ft"] = station["elevation_m"] * 3.28084
  • Access by name, not by position
  • New derived entries can be added any time
03 · Dictionaries

Looping over a Dictionary

Python

for key, value in station.items():
    print(key, "=", value)

# id = IOW
# latitude = 41.64
# longitude = -91.54
# elevation_m = 204.0
# elevation_ft = 669.29
  • .items() hands you each pair in turn
03 · Dictionaries

List or Dictionary?

List

Ordered sequence. Ask by position: temps[0]. Seven days of temperature.

Dictionary

Labeled storage. Ask by name: station["id"]. One station's metadata.

Rule of thumb

Which one? Ask how you would request an item: by position, list; by name, dict.

Pause and think

?

You need latitude, longitude, and elevation for 17 stream stations. What structure fits: one list, one dictionary, or a dictionary per station inside a list?

A list of dictionaries: ordered stations, labeled fields
Preview: a pandas DataFrame is exactly this idea, industrialized
04

Putting It Together

Where pandas stops, plain Python starts, and how conversions go wrong.

04 · Putting it together

From Pandas to Plain Python and Back

Pull values out

  • weather.iloc[0]["temp_mean_c"] gives one number
  • .head(7).tolist() gives a plain list
  • Then ordinary Python arithmetic takes over

Why practice both

  • pandas for tables, Python for logic
  • Knowing the boundary prevents type confusion
  • type(x) answers any doubt
04 · Putting it together

The Errors You Will Meet This Week

  • TypeError: adding a string to a number (fix: f-string)
  • IndexError: asking for temps[7] in a 7-item list
  • KeyError: station["elevation"] when the key is elevation_m
  • Silent wrong factor: a conversion that runs and lies
04 · Putting it together

Sanity Anchors for Conversions

  • Room temperature: about 20 deg C = 68 deg F
  • A 10 m/s wind: about 22 mph
  • Iowa City elevation: about 200 m = 670 ft
  • A converted number that breaks intuition means a wrong factor
04 · Putting it together

The Station Report, End to End

01

Given

First row of the weather table: station id, coordinates, elevation in meters.

02

Solve

Build a dictionary, add elevation_ft as a derived entry, loop and print each pair.

03

Interpret

One f-string sentence: station, elevation in both units, formatted to sensible precision.

04 · Putting it together

Lab 2, Part A: Python Basics with Weather Variables

Lab session

  • Temperature conversion with variables
  • First-week list: index, slice, manual mean
  • Station metadata dictionary

More practice (Friday)

  • Windiest day in m/s and mph
  • Ten-day precipitation list arithmetic
  • One f-string sentence with two units

Lab 2 continues as Part B in Week 3: one notebook, two graded checkpoints.

Bridge

Connection to Next Week

This weekNext weekBridge idea
Store and label single valuesConditionals and loopsFrom holding data to making decisions over it
Summary

Key Takeaways

  • Names carry units: temp_c, elevation_ft
  • Lists index by position; slices stop before the end index
  • Dictionaries label values by name
  • f"{x:.1f}" prints values at honest precision
  • Two routes to one number is a correctness test
Discussion · Next week: conditionals and loops

?

Name one quantity from your own field and the variable name you would give it, unit included.