Functions and Methods
Parameters, return values and scope.
A function is a named, reusable block of code that takes inputs (parameters), does some work and usually returns an output. Functions let you write a piece of logic once, test it in isolation and call it from many places, which makes programs shorter and easier to reason about.
Variables created inside a function are local: they exist only while the function runs and cannot be seen from outside. Values passed in are the arguments. Understanding the difference between returning a value and printing it, and between local and global scope, removes a large share of beginner bugs.
Key ideas
- A function signature names the function, its parameters and (in typed languages) its return type.
- `return` ends the function immediately and hands back a value.
- Pure functions depend only on their inputs and have no side effects, which makes them easy to test.
- Methods are functions attached to objects, called as `object.method()`.
Worked example
Given `def area(w, h): return w * h`, what is `area(3, area(2, 5))`?
- Evaluate the inner call first: `area(2, 5)` returns 10.
- Then `area(3, 10)` returns 30.
Answer:
Common mistakes
- Printing a value inside a function and expecting the caller to receive it.
- Changing a local variable and expecting a global with the same name to change.
- Calling a function with arguments in the wrong order.
Practice questions
Try each one, then open the answer. Numerical answers on this page are verified by an automated calculation check.
1.If `f(x) = 2 * x + 1`, what is `f(f(3))`?
Show answer
2.If `sq(n) = n * n`, what is `sq(4) + sq(5)`?
Show answer
3.Does a function without a return statement give back a useful value?
Show answer
No; it returns a default such as None or undefined