Functions
Package code into reusable functions with parameters, defaults and return values.
18 min
A function is a named, reusable block of code. You have already called several: print, len, round. Now you write your own:
def greet(name):
return "Hello, " + name + "!"
message = greet("Ada")
print(message) # Hello, Ada!defstarts the definition; the indented lines are the body.nameis a parameter: a variable that holds whatever you pass in.returnhands a value back to the caller and ends the function.
print shows a value to a human. return gives it to the code that called the function. A function that only prints returns None, so you cannot use its result in a sum, compare it or store it for later. Most functions should return and let the caller decide what to print.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Ada") # Hello, Ada!
greet("Ada", "Hi") # Hi, Ada!
greet(greeting="Hey", name="Bo") # Hey, Bo!Parameters with a default must come after those without.
Variables created inside a function exist only while it runs. The function sees its own variables and its parameters; changing a name inside does not change a name outside. That separation is what lets you reuse a function safely.
“A function that prints the answer has given me the answer.”
On screen it looks the same: you see the number.
What is actually true
Printing displays text; it does not hand a value to the caller. x = double(4) stores None if double only prints, and then x + 1 crashes.
How to catch yourself
If a result is `None` when you expected a value, look for a missing `return`.
double(x) should return twice its input, but the program that calls it crashes when it adds 1 to the answer. Fix the function.
What it does now
double(4) + 1 raises TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'.
Your code must satisfy
- double(4)→8four
- double(0)→0zero
- double(-3)→-6negative
- double(1.5)→3float
def double(x):
print(x * 2)Write greet(name, greeting="Hello") that returns "Hello, Ada!" for greet("Ada") and "Hi, Ada!" for greet("Ada", "Hi").
Your code must satisfy
- greet("Ada")→"Hello, Ada!"default
- greet("Ada", "Hi")→"Hi, Ada!"custom
- greet("Bo", greeting="Hey")→"Hey, Bo!"keyword
def greet(name, greeting="Hello"):
passWrite clamp(x, low, high) that returns x limited to the range from low to high: below low gives low, above high gives high, otherwise x.
Your code must satisfy
- clamp(5, 0, 10)→5inside
- clamp(-4, 0, 10)→0below
- clamp(99, 0, 10)→10above
- clamp(10, 0, 10)→10on the edge
- clamp(-7, -5, -1)→-5negative range
def clamp(x, low, high):
passA good function
def name(parameters):defines a function andreturnhands back a value and ends it.- A function with no
returngives backNone: print shows, return gives. - Defaults make a parameter optional:
def f(a, b=10). - Names created inside a function stay inside it.
Function checks.
What does a function return if it has no return statement?
- A0
- B""
- CNone
- DAn error is raised
Which call is valid for def f(a, b=2):?
- A`f()`
- B`f(1)`
- C`f(b=3)`
- D`f(1, 2, 3)`
def f(x): return x * 2 + 1. What is f(f(1))?
The keyword that sends a value back to the caller is .
Capitalisation, spacing and punctuation are ignored when grading.
Which statements about return are true?
- AIt ends the function immediately
- BIt prints the value on screen
- CThe caller can store its value in a variable
- DA function can have more than one
Look at something you did in earlier lessons that you repeated by copy and paste. What would you name the function, and what would its parameters be?
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Python for Complete Beginners is planned around your week. Free.