Courses / Computer Science I
Programming I

Functions and Parameter Passing

Computer Science I 266 words Free to read

Packaging Logic

A function is a named, reusable block of code that performs a task. Defining a function once and calling it many times avoids repetition and gives a piece of logic a meaningful name — the foundation of organized programming.

def square(n):
    return n * n

y = square(5)   # y becomes 25

A function may take parameters — named inputs listed in its definition (n above). When you call it, you supply arguments — the actual values passed in (5 above). Inside, the parameter behaves like a local variable holding that argument. A function may return a value with return, which both ends the function and hands a result back to the caller; a function with no return yields nothing useful.

Scope governs where names are visible. Variables created inside a function are local — they exist only during the call and are invisible outside. This is a feature: it lets functions work without clobbering each other's variables. A variable declared outside all functions is global, visible everywhere (but relying on globals makes code harder to reason about).

Functions enable abstraction: a caller uses square(5) without caring how it computes the square, just as you use a phone without knowing its circuitry. Well-chosen functions turn a big problem into small, named, testable pieces.

Common pitfall: confusing parameters (the names in the definition) with arguments (the actual values in the call). def f(x) declares a parameter x; f(10) passes the argument 10. Also, expecting to use a function's local variables from outside the function — they simply do not exist there.

Practise this lesson

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

11practice questions
2interactive scenes
Start Computer Science I free

Programming I