S12 · Computer Studies I · Grade 10 · ages 15–16
Functions
Modular programming
Grade 10 · 3.6 FunctionsCBE strandFree · works offline
▶ Start the interactive lessonThe full lesson adds narration, an interactive mission and a 10-question bank, and the quiz explains any mistakes.
Why functions?
A function is a named block of code that does one job. Modular programming breaks a big program into functions, so each part is easier to write, test, fix and reuse. It is like a school: each department does its own job, and together they run everything.
Built-in and user-defined
Built-in functions come with Python: print(), input(), len(), int(), max(), round(). User-defined functions are the ones you write yourself with def. Once defined, you can call your function as many times as you like.
Defining a function
def area(length, width): return length * width. This defines a function named area with two parameters. Calling area(3, 4) passes 3 and 4 in as arguments, and the function returns 12. Inside a real program, the body goes on its own indented lines under the def line.
Parameters and return values
Parameters are the names in the definition (length, width); arguments are the actual values you pass in (3, 4). return sends a result back to the caller and ends the function. A function without return gives back the special value None.
Scope: local and global
A variable created inside a function is local: it exists only while the function runs and can't be used outside it. A variable created outside all functions is global. Prefer passing values in as parameters and returning results; it keeps functions independent and easy to test.
Key points
- A function is a named block of code that does one job.
- Modular programs are easier to write, test, fix and reuse.
- Python has built-in functions like print and len, and you can write your own with def.
- Parameters are names in the definition; arguments are the values you pass in.
- return sends a result back and ends the function.
- Variables made inside a function are local to it.
- Pass values in and return results, so functions stay independent.
Try it for real: Write a fees function
- If you can, open Python and write a function fees_due(paid, total) that returns the balance. Test it with fees_due(15000, 40000).
- Write a function is_even(n) that returns True if n is even. Hint: use %.