3.1  Best practices

Your goal is to write code that is correct, readable, and reproducible.

Readability: Code is for Humans

You’ll spend more time reading code than writing it. Use variable names that describe what they represent.

# Hard to read:
r = 10
h = 5
v = 3.14 * r**2 * h

# Better:
radius = 10.0
height = 5.0
cylinder_volume = 3.14159 * radius**2 * height

DRY: Don’t Repeat Yourself

If you’re copying and pasting code, write a function instead. One fix beats five.

KISS: Keep It Simple Stupid

A simple solution that works beats a clever one that’s hard to debug.

RTFM: Read The Fucking Manual

Learn how to find and read documentation.

Style Matters (PEP 8)

Python’s style guide is PEP 8. For variable and function names, use snake case: particle_velocity, calculate_area. Put spaces around operators: y = m * x + b.

Comments: The “Why”, not the “What”

# Bad: restates the obvious
# Multiply mass by acceleration
force = mass * acceleration

# Good: explains the physics
# Newton's Second Law: F = ma
force = mass * acceleration

Comments are also useful for documenting units:

g = 9.81  # [m/s^2]

Your Lab Notebook: Marimo

We use Marimo notebooks because they guarantee code runs in order—no hidden state bugs. The recommended workflow: setup (constants, initial values) → model (functions) → calculations → visualization.

When a function appears across multiple notebooks, move it to a .py file and import it. If your notebook exceeds a few hundred lines, consider splitting it up.

Verification

Unit Analysis

Track your units. You can’t add meters to seconds. Include units in comments or variable names (time_s, distance_m), then verify your final answer has the expected dimensions.

Reasonability Checking

Test edge cases: zero radius should give zero area. Check bounds: probabilities must be in [0, 1]. For geometry: the hypotenuse is always the longest side.

Visualization

Plot your results. Does the curve have the expected shape? Do vectors point the right direction? Does the trajectory look physical?

Saving Your Work (Git)

Use Git to version your work. Commit after finishing each problem or fixing a bug.

Testing

Validate against problems you can solve by hand. Sanity checks like \(\sin^2(x) + \cos^2(x) = 1\) should return exactly 1.0.