Quiz
Warm-up from lesson 7-1: `ages.get("Linus", 0)` returned 0 instead of crashing. What is the second value you pass to get for?
A function is a named, reusable block
By now some of your programs repeat the same few lines with tiny changes, and repetition is where bugs breed: fix one copy, forget the other. Functions exist to kill that duplication: define the step once, name it, reuse it everywhere, fix it in one place. Every library you will ever import is a pile of functions somebody defined, so this lesson is also how you will read other people's code.
You have been calling functions all course: print(), len(), input(). Now you get to define your own with def:
def area(w, h): return w * h
areais the function's name.wandhare parameters: placeholder variables for the inputs.returnsends a value back to whoever called.
Defining runs nothing. The body executes only when you call it, and the values you pass, the arguments, get assigned to the parameters:
print(area(3, 4)) # w becomes 3, h becomes 4, back comes 12
Write a function whenever the same few lines would otherwise be pasted twice, or when naming a step (area, greet) makes the program read like a plan.
Code exercise · python
Run this. Two definitions, three calls. Note that nothing prints until the calls at the bottom.
Code exercise · python
Your turn. Define `circumference(r)` that returns 2 × 3.14159 × r. Call it with r = 10 and print the result.
Default values and keyword arguments
A parameter can carry a default value, written with = in the def line. The default is used whenever the caller leaves that argument out. Defaults exist so the common call stays short while the unusual call stays possible:
def greet(name, greeting="Hello"): return f"{greeting}, {name}!" greet("Ada") # Hello, Ada! greet("Ada", "Welcome") # Welcome, Ada!
You can also name arguments at the call site, called keyword arguments: greet(greeting="Hi", name="Grace"). With a keyword argument the name, not the position, decides which parameter receives the value. Real code uses this to keep calls readable, and print itself accepts one: print("a", "b", sep="-") prints a-b, where sep replaces print's default separator, a space.
Code exercise · python
Your turn. Define `power(base, exp)` where `exp` defaults to `2`, returning base ** exp. The two given calls should then print 25 (the default squares) and 1024.