Skip to content
Lesson 8 of 10 · Python for Complete Beginners

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:

python5 lines
def greet(name):
    return "Hello, " + name + "!"

message = greet("Ada")
print(message)        # Hello, Ada!
  • def starts the definition; the indented lines are the body.
  • name is a parameter: a variable that holds whatever you pass in.
  • return hands 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.

python6 lines
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.

Common misconception

“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`.

Exercise4 checks
python

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
starter code2 lines
def double(x):
    print(x * 2)
Exercise3 checks
python

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
starter code2 lines
def greet(name, greeting="Hello"):
    pass
Exercise5 checks
python

Write 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
starter code2 lines
def clamp(x, low, high):
    pass
Checklist
0/4

A good function

  • def name(parameters): defines a function and return hands back a value and ends it.
  • A function with no return gives back None: print shows, return gives.
  • Defaults make a parameter optional: def f(a, b=10).
  • Names created inside a function stay inside it.
Check yourself

Function checks.

1Multiple choice

What does a function return if it has no return statement?

  • A0
  • B""
  • CNone
  • DAn error is raised
2Multiple choice

Which call is valid for def f(a, b=2):?

  • A`f()`
  • B`f(1)`
  • C`f(b=3)`
  • D`f(1, 2, 3)`
3Numeric answer

def f(x): return x * 2 + 1. What is f(f(1))?

4Fill the blanks

The keyword that sends a value back to the caller is .

Capitalisation, spacing and punctuation are ignored when grading.

5Select all that apply

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
For you · never graded

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.