Courses / Physics I
Computer Science

Functions and modular decomposition

Physics I 222 words Free to read

A function encapsulates a reusable block of logic. It takes parameters, performs a computation, and returns a result.

def kinetic_energy(mass, velocity):
    # Compute KE = (1/2)mv^{2}
    return 0.5 * mass * velocity**2

Why functions matter in physics

Scope — Variables defined inside a function are local; they do not exist outside it.

def f(x):
    result = x ** 2    # 'result' is local to f
    return result

# print(result)  → NameError!

Modular decomposition — Break a complex problem into smaller functions, each solving one sub-task:

main_simulation()
├── initialise_state()
├── compute_forces()
├── update_positions()
└── write_output()

Pure vs impure functions — A pure function depends only on its inputs and has no side effects. Pure functions are easier to test and debug.

Key insight: If you find yourself copy-pasting code, extract it into a function. The DRY principle (Don't Repeat Yourself) reduces bugs and simplifies maintenance.
Common pitfall: A function that prints a result and one that returns it look identical when run alone — but only the returner composes with other code. Printing is for humans; returning is for programs.

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

14practice questions
2interactive scenes
Start Physics I free

Computer Science