Parameters and arguments
🌍 In real life. A tea-stall order isn't just "tea": it's "tea, with milk, two sugars". The recipe is the same every time, but some blanks are filled in differently for each order.
Functions have blanks like that too, called parameters.
The idea in one sentence: the names in the def brackets are parameters, the values in a call's brackets are arguments, and each call fills each parameter with its argument, in order.
Its words:
- parameter: a name in the definition,
def greet(name): - argument: a value in the call,
greet("Ana") - binding: putting an argument into its parameter when the call starts
Step by step, for describe("cat", "meow"):
- The first argument,
"cat", goes to the first parameter,animal. - The second,
"meow", goes tosound. - The body runs with those values.
def greet(name):
print("Hi,", name)
greet("Ana")
greet("Bo")With several parameters, the arguments are matched in order: the first argument goes to the first parameter, and so on.
def describe(animal, sound):
print("The", animal, "says", sound)
describe("cat", "meow")
describe("meow", "cat")Giving too few (or too many) arguments stops the program with a TypeError:
def describe(animal, sound):
print("The", animal, "says", sound)
describe("cat")How Python does it. Each call gets its own fresh set of parameters: calling greet("Ana") and then greet("Bo") doesn't mix them up, because the first call's name is gone when it ends. The match is purely by position: Python doesn't look at what the values mean.
Mistakes and edge cases.
- Too few arguments.
describe("cat")givesTypeError: describe() missing 1 required positional argument: 'sound'(above). - Too many.
describe("cat", "meow", 2)givesTypeError: describe() takes 2 positional arguments but 3 were given. - The wrong order. Swapped arguments give no error, just a wrong result: "The meow says cat".
- Using a parameter outside its function.
nameexists only whilegreetis running (Chapter 15 explains why).
Quiz
What does this print?
def show(x): print(x * 2) show(4) show("ab")What does this print?
def minus(a, b): print(a - b) minus(10, 3) minus(3, 10)In
def area(w, h):andarea(3, 4), what are3and4?- Arguments
- Parameters
- Function names
Which line has a mistake?
def add(a, b): print(a + b) add(1)What does this print?
def stars(n): print("*" * n) for i in range(1, 4): stars(i)
Coding tasks
Define
greet(name)that printsHello, <name>!(for exampleHello, Ana!). Then ask for a name and callgreetwith it.Define
rectangle(w, h)that prints the areaw * h. Ask for a width and a height on one line, and callrectanglewith them as numbers.Define
repeat(word, times)that printswordrepeatedtimestimes, joined into one line (forrepeat("ab", 3)it printsababab). Ask for a word, then a number, and call it.