Find a course

Module 4: Lists, Functions and Your First ProjectLesson 9 of 1013 min

Writing Your Own Functions

Define functions with def, pass in parameters, send results back with return, and understand why variables inside a function stay inside it.

Step 1 of 15Learn

Build your own tools

You've been using functions since the first lesson: print(), input(), len(), randint(). Each one packages a job behind a name. Now you'll write your own.

def greet(name):
    print(f"Hey {name}, welcome back!")

greet("Sam")
greet("Priya")

The first line starts with def (define), then the function's name, then parameters in parentheses, then a colon. The indented block below is the function's body.

Defining a function doesn't run it. It just teaches Python a new command. The body runs only when you call the function by writing its name with parentheses. Each call passes an argument (here "Sam", then "Priya") into the parameter name.

Why bother? Three reasons:

  • Reuse: write the code once and call it from many places.
  • Fix once: if there's a bug, you fix it in one place, not in five copies.
  • Readability: a call like show_menu() explains itself, hiding the details until you need them.

A function can have several parameters, separated by commas: def area(width, height):. The arguments are matched in order.

Step 2 of 15Practice · Diagram

Anatomy of a function

Which part gets a different value every time you call the function?

Tap the shape that answers the question, then press Check.

Anatomy of a functionParts diagram: def greet(name):, def, Function name, Parameter, Indented body, The call.defgreet(name):defFunction nameParameterIndented bodyThe call
def greet(name):
def

Tells Python you are defining a new function.

Function name

greet: follows the same rules as variable names.

Parameter

name: a placeholder filled in each time you call it.

Indented body

The code that runs on every call.

The call

greet("Zoe") runs the body with name = "Zoe".

Step 3 of 15Practice · Put in order

Put the lines in order to define a function and then call it.

Drag the items, or use the arrow buttons, to put them in order.

  1. print("Go!")
  2. def cheer(team):
  3. cheer("Tigers")
  4. print("Go", team)

Step 4 of 15Learn

Sending results back with return

greet prints something, but many functions should hand a result back so the rest of your program can use it. That's what return does:

def area(width, height):
    return width * height

room = area(4, 5)
print(room)                  # 20
print(area(3, 3) + area(2, 6))  # 9 + 12 = 21

When Python reaches return, it leaves the function immediately and the call is replaced by the returned value. That's why area(4, 5) can be stored in a variable or used in a calculation, just like the result of len().

print is not return. This is the biggest beginner confusion with functions:

def double_print(n):
    print(n * 2)

def double_return(n):
    return n * 2

x = double_print(5)    # shows 10, but x is None
y = double_return(5)   # shows nothing, but y is 10

print shows a value to a human. return gives a value to the code. A function without return gives back None. If you need to use the result later, you need return.

Step 5 of 15Diagram

Following room = area(4, 5)

Following room = area(4, 5)Process diagram: Call area(4, 5) → width = 4, height = 5 → Work out 4 * 5 → return 20 → room = 20.Call area(4, 5)width = 4, height = 5Work out 4 * 5return 20room = 20

Tap a shape with to see more.

Call area(4, 5)
width = 4, height = 5

Arguments fill the parameters in order.

Work out 4 * 5
return 20

The function ends here and hands 20 back.

room = 20

The call is replaced by the returned value.

Step 6 of 15Practice · Work it out

What does this print? `` def score(kills, deaths): return kills * 100 - deaths * 50 total = score(6, 2) + score(3, 4) print(total) ``

Step 7 of 15Practice · Choose one

A function ends with print(result) instead of return result. What happens with answer = my_func(4)?

Step 8 of 15Practice · Code challenge · Python

Code challenge · Python

Write the function level_up(xp). Every player starts at level 1, and every full 100 XP adds one level. Return the player's level as a whole number.

For example, level_up(250) returns 3, and level_up(99) returns 1. Remember: return the value, don't print it.

Real Python, running in a sandbox in your browser.
  • level_up(250)
  • level_up(0)
  • level_up(99)
  • level_up(100)
  • level_up(1999)

Step 9 of 15Learn

Scope: what happens in a function stays there

Variables created inside a function are local: they exist only while the function runs.

def make_bonus():
    bonus = 500
    return bonus

make_bonus()
print(bonus)   # NameError: name 'bonus' is not defined

bonus disappeared when the function finished. To use the value outside, catch what the function returns: bonus = make_bonus().

This isolation is a feature. You can use a variable called total in ten different functions without them interfering, because each has its own private total.

Parameters are local too. Changing a parameter inside the function doesn't change the variable you passed in:

def level_up(level):
    level = level + 1
    return level

lvl = 4
level_up(lvl)
print(lvl)        # still 4
lvl = level_up(lvl)
print(lvl)        # now 5

The second call works because the returned value is stored back in lvl. The general rule: data goes into a function through parameters and comes out through return.

Step 10 of 15Compare

Local vs. global variables

AspectLocal (inside a function)Global (top level)
CreatedInside def, when it runsOutside any function
Lives untilThe function finishesThe program ends
Visible fromOnly that functionEverywhere (readable)
Getting a value outreturn itAlready available

Step 11 of 15Practice · True or false

A variable created inside a function can be printed after the function has finished running, as long as the function was called first.

Step 12 of 15Practice · Fill in the blanks

Fill in the blanks

Complete the function so is_even(10) gives True and is_even(7) gives False. is_even(n): n % 2 == 0

Step 13 of 15Note

Step 14 of 15Practice · Spot the mistake

This function should return the larger of two numbers. Tap the lines with bugs.

Step 15 of 15Practice · What would you do?

What would you do?

Ben writes a tip calculator:

def tip(bill):
    t = bill * 0.18
    return t
    print("Tip calculated!")

He never sees "Tip calculated!" on screen. Why?