Python syntax map¶
Use this as a lookup after the course gives you a reason for the syntax.
Bind a name¶
The name now refers to a value. Python does not encode units, so the name or a units library must.
Make a sequence¶
Lists are ordered and mutable. Tuples are ordered and normally used for fixed records:
Map names to values¶
Branch on a condition¶
if time_step <= 0:
raise ValueError("time step must be positive")
elif time_step < warning_limit:
warn()
else:
continue_normally()
Indentation defines the block.
Repeat¶
Use enumerate when both index and item matter:
Use while when termination depends on changing state:
Always plan a maximum iteration count.
Define a function¶
def weber(density, speed, length, surface_tension):
return density * speed**2 * length / surface_tension
Keyword-only policy arguments follow *:
Fail deliberately¶
Catch only errors you can handle:
try:
value = float(text)
except ValueError as error:
raise ValueError(f"bad value: {text!r}") from error
Work with files¶
For structured CSV, use csv.DictReader, NumPy, or pandas with a declared
schema.
Build arrays¶
Important attributes:
Import¶
The imported name becomes available in the current module. Avoid wildcard imports; they hide provenance.
Main guard¶
This lets the file act as a command while keeping functions importable for tests.
Tests¶
The test name states the claim. pytest.approx handles floating-point
comparison with a tolerance.
Formatting strings¶
Use formatting for presentation, not before numerical operations.
Type hints¶
Hints document intent and help tools. Python does not enforce them at runtime. Validation is still required at external boundaries.