Find a course

Module 5: Functions, Errors, Files and ModulesLesson 11 of 1213 min

Writing Your Own Functions

Define functions with def, pass arguments, return results instead of printing them, use default and keyword arguments, and understand local scope.

Step 1 of 14Learn

Name a piece of code, reuse it anywhere

Lena's script calculates sales tax in six different places with the same three lines. When the tax rule changes, she updates five of them and misses one. Functions fix this: write the logic once, give it a name, and call that name wherever you need it.

def add_tax(amount, rate):
    tax = amount * rate
    return amount + tax

print(add_tax(100, 0.08))     # 108.0
print(add_tax(250, 0.05))     # 262.5

The anatomy of a function:

  • def starts the definition, followed by the function's name and parentheses.
  • Inside the parentheses are parameters: names that will receive the inputs, here amount and rate.
  • The line ends with a colon, and the body is indented.
  • return sends a result back to whoever called the function.

Defining a function doesn't run it. The body runs only when the function is called: add_tax(100, 0.08). The values in the call, 100 and 0.08, are the arguments; they're assigned to the parameters in order, and the body runs with them.

A function must be defined before the line that calls it runs, which is why scripts usually put their function definitions at the top. You've been calling functions all along (print, len, input); now you can make your own.

Step 2 of 14Diagram

What happens when you call a function

What happens when you call a functionProcess diagram: Call: with_tax(100) → Parameter amount = 100 → Body runs → return 108.0.Call:with_tax(100)Parameteramount =100Body runsreturn 108.0

Tap a shape with to see more.

Call: with_tax(100)

Arguments are passed in.

Parameter amount = 100

A local name inside the function.

Body runs

amount * 1.08

return 108.0

The value goes back to where the call was written.

Step 3 of 14Learn

return is not print

The most important distinction for new programmers: print shows a value to a human; return hands a value back to the program.

def area_print(w, h):
    print(w * h)

def area_return(w, h):
    return w * h

a = area_print(3, 4)     # shows 12 on screen
b = area_return(3, 4)    # shows nothing
print(a)                 # None
print(b)                 # 12
print(b * 2)             # 24

area_print displays 12, but the program gets nothing back. A function without a return statement returns the special value None, so a is None and a * 2 would crash with a TypeError. area_return prints nothing, but its result can be stored, compared, added and passed to other functions: total = area_return(3, 4) + area_return(5, 2).

Rule of thumb: functions that calculate should return, and the code that uses them decides whether to print. That keeps functions reusable in places where printing would be wrong, such as a web page or a file.

return also ends the function immediately. Any lines after it in the same block never run. That's handy for early exits: if amount < 0: return 0 at the top of a function handles a bad input before the main work begins.

Step 4 of 14Compare

print vs return

Aspectprint(x)return x
Who gets the valueA human, on screenThe code that called the function
Function resultNone (if nothing is returned)x
Can be stored or reusedNoYes: total = f(3)
Ends the functionNoYes, immediately

Step 5 of 14Practice · What would you do?

What would you do?

What does this program print?

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

result = double(5)
print(result)

Step 6 of 14Learn

Parameters, defaults and keyword arguments

Functions become much more flexible with a few parameter features.

Default values make a parameter optional:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet("Ana")               # 'Hello, Ana!'
greet("Ana", "Welcome")    # 'Welcome, Ana!'

Parameters with defaults must come after those without them.

Keyword arguments name the parameter in the call, so order no longer matters and calls explain themselves:

greet(greeting="Hi", name="Ben")       # 'Hi, Ben!'
add_tax(amount=80, rate=0.06)

You've seen this with built-ins: sorted(names, reverse=True) and print(x, end=" ").

Calling with the wrong number of arguments raises a TypeError that tells you exactly what's missing, such as "greet() missing 1 required positional argument: 'name'".

A function can also return several values as a tuple, which the caller unpacks:

def stats(nums):
    return min(nums), max(nums), sum(nums) / len(nums)

low, high, avg = stats([4, 9, 2])

Finally, document what a function does with a docstring, a string right under the def line: """Return amount plus tax at the given rate.""". Editors show it when you hover over the function, and help(add_tax) prints it.

Step 7 of 14Practice · Code challenge · Python

Complete apply_discount(price, percent=10) so it returns the price after taking percent percent off. The percent parameter has a default value of 10, so apply_discount(50) returns 45.0.

Real Python, running in a sandbox in your browser.
  • apply_discount(50)
  • apply_discount(80, 25)
  • apply_discount(19.99, 0)
  • apply_discount(40, percent=100)

Step 8 of 14Practice · Choose one

Given def label(item, price, currency="USD"): return f"{item}: {price} {currency}", what does label("Pen", currency="EUR", price=2) return?

Step 9 of 14Learn

Scope: where variables live

Variables created inside a function are local: they exist only while the function runs and are invisible outside it.

def make_total(prices):
    total = sum(prices)
    return total

make_total([3, 4])
print(total)        # NameError: name 'total' is not defined

This is a feature, not a limitation. Each function is a sealed workspace, so a variable called total inside one function can't accidentally clash with a total somewhere else. Parameters are local variables too.

A function can read variables defined at the top level of the script (globals), but relying on that makes code hard to follow, because the function's result then depends on something not visible in its call. If you assign to a name inside a function, Python treats it as a new local variable, even if a global with the same name exists, which leads to confusing bugs.

The clean approach is simple: pass information in through parameters and send results out with return. A function that only uses its parameters and returns its result is easy to understand, test and reuse.

TAX_RATE = 0.08                      # a constant is fine to read

def price_with_tax(amount, rate=TAX_RATE):
    return round(amount * (1 + rate), 2)

Constants written in ALL_CAPS, which never change, are the accepted exception to "avoid globals".

Step 10 of 14Practice · Diagram

Where Python looks up a name

In make_total, where does the name total live?

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

Where Python looks up a nameLayer diagram: Local: inside the function, Enclosing function, Global: top of the script, Built-in.Local: inside the functionEnclosing functionGlobal: top of the scriptBuilt-in
Python checks from the top layer down and uses the first match.
Local: inside the function

Parameters and variables assigned in the function.

Enclosing function

Only for functions defined inside other functions.

Global: top of the script

Names like TAX_RATE defined outside any function.

Built-in

print, len, sum and friends.

Step 11 of 14Practice · True or false

A variable created inside a function can be used by code after the function call, as long as the function has already run.

Step 12 of 14Learn

Designing good functions

Writing a function is easy; writing a good one takes a few habits.

  • One job per function. calculate_total, format_receipt and save_receipt are three functions, not one. Small functions are easier to name, test and reuse.
  • Names that start with a verb describe the action: get_user, is_valid_email, convert_to_celsius. Functions that answer yes/no questions often start with is_ or has_ and return a Boolean.
  • Return, don't print, unless the function's whole purpose is output.
  • Handle edge cases: an empty list, a zero, a negative number. What should average([]) do? Decide, and make it happen on purpose rather than by crashing.

Functions also make code testable. A quick way to check one is with assert, which raises an error if a condition is false:

def to_celsius(f):
    return (f - 32) * 5 / 9

assert to_celsius(32) == 0
assert to_celsius(212) == 100

If both lines run silently, the function passed. Professional projects use testing frameworks built on the same idea.

Finally, once you have functions, the main part of a script often shrinks to a few readable lines that call them in order, reading almost like a summary of what the program does.

Step 13 of 14Practice · Put in order

Put these lines in order so the program defines a function and then prints the area of a 4 by 5 room.

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

  1. print(room)
  2. (indented) return width * height
  3. room = area(4, 5)
  4. def area(width, height):

Step 14 of 14Practice · Fill in the blanks

Fill in the blanks

With def double(n): return n * 2, the call double(double(3)) returns .