Functions and lists in Python

Computer Science · Key Stage 3 · The School

Functions: name a piece of work

def area(width, height): return width * height. The name says what it does, the parameters are what it needs, and return sends the answer back. Now area(3, 4) works anywhere. If the calculation is ever wrong, there is exactly ONE place to fix it — that is the real reason functions exist.

Lists hold many values

scores = [7, 9, 4]. Index from ZERO: scores[0] is 7. append() adds, len() counts. Loop with for s in scores: print(s). Lists plus loops are what let a program handle a hundred items with the same code as three — the moment a program stops being a calculator and starts being useful.

Do not repeat yourself

If you paste the same three lines four times, four bugs are waiting for you. Put them in a function and call it four times. Programmers say "DRY — don't repeat yourself", and it is not about typing less; it is about having one place to be correct.

Write a function `def greet(name): print("Hello " + name)` and run the file: no error, and no output either. The function was DEFINED and never CALLED. Add one line at the bottom — `greet("Amir")` — and it prints. Now note the parameter: `greet("Sara")` prints something different from the same function, because the value is handed in at the call. One definition, many calls, which is the entire reason functions exist.

The School — all subjects · Knowledge map