Courses / Physics I
Computer Science

Functions and modular decomposition

Physics I 183 words Free to read

A function encapsulates a reusable block of logic, taking parameters, computing, and returning a result.

def kinetic_energy(mass, velocity):
    return 0.5 * mass * velocity**2

Scope: Variables defined inside are local and do not exist outside.

def f(x):
    result = x ** 2
    return result
# print(result) -> NameError!

Modular decomposition breaks complex problems into smaller functions solving single sub-tasks.

A function is a sealed machine; a name born inside it dies with the call

Purity and Pitfalls

Function TypeBehaviorTesting
PureDepends only on inputs, no side effectsEasy to test
ImpureModifies external state or relies on globalsHarder to test

DRY Principle: Don't Repeat Yourself. If you copy-paste code, extract it into a function to reduce bugs and ease maintenance.

Common Pitfall: A function that prints versus one that returns. Printing is for humans to read, but only returning lets code compose functions together. Always return values for program use.

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

Computer Science