Functions and Objects · Functions · lesson 1 of 10
def and return
about 12 minutes · free · runs in your browser
Step 1 of 2
Defining a function
def area(width, height):
return width * height
def starts the definition, then the name, then the parameters in brackets. The
indented block is the body. Calling it — area(3, 4) — runs the body with width set
to 3 and height set to 4.
return hands a value back and stops the function immediately. Any code after a
return that runs will never execute.
A function with no return gives back None. That is the single most common source of
confusion early on: print() shows a value, return gives it to the caller, and they
are not the same thing. A function that only prints returns None.
Your turn: write rectangle_area(width, height) returning the area, and
describe(width, height) returning a string like "3 x 4 = 12".
You start from this, and edit it in the browser:
def rectangle_area(width, height):
pass
def describe(width, height):
pass
Step 2 of 2
Returning early
Handling the awkward cases first, and returning straight away, keeps the main body of a function unindented and easy to follow:
def divide(a, b):
if b == 0:
return None
return a / b
This is usually called a guard clause. Compare it with wrapping everything in an
else — the guard version stays flat no matter how many cases you add.
Your turn: write safe_average(numbers) returning the mean, or None for an
empty list.
You start from this, and edit it in the browser:
def safe_average(numbers):
# Return the mean, or None for an empty list.
pass