Skip to main content

Programming fundamentals · Beginner · 18 min

Write functions that return values instead of printing them

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will turn print-only functions into ones that return values, use parameters, defaults, keyword arguments and tuples, fix the UnboundLocalError, and end with four documented functions you can call and combine from the Python REPL.

On this page

A function that prints its answer is a dead end. The number appears on the screen, and then it is gone: your program cannot add it to a total, compare it with a limit or pass it to another function. A function that returns its answer hands the value back to the code that called it, and that code decides what happens next, including whether to print it.

In this tutorial you write two small tools, a temperature converter and a VAT calculator, first the print-only way, so you see exactly where it breaks. Then you rewrite them to return values and add the features that make functions pleasant to use: default values, keyword arguments, several results at once, and docstrings. Along the way you meet scope, the rule for which variables a function can see, and the UnboundLocalError that catches almost every beginner once.

The VAT examples use 7.5% as the default rate and other rates as samples. Use your own country's rate, and amounts in your own currency (naira, cedis, shillings, rand, pounds): the code does not care.

The commands are for a bash terminal: Linux, macOS or WSL on Windows. They create each file with cat > file.py <<'PY', which does not work in PowerShell or Command Prompt. If you work on Windows without WSL, create each file in your editor by pasting the lines between <<'PY' and the closing PY, then run it with py file.py instead of python3 file.py.

On an Android phone, the Termux app can install Python with pkg install python, and everything here then runs offline without using mobile data. Termux installs whichever Python version it currently packages, which may not be 3.15, so some error messages may read slightly differently from the ones shown here.

Step 1 · Write a function that prints, and try to reuse it

Make a folder for this tutorial and write the first version of both tools. Each function does its sum and prints the answer:

Bash
mkdir -p ~/functions-demo
cd ~/functions-demo
cat > printing.py <<'PY'
def celsius_to_fahrenheit(celsius):
    print(celsius * 9 / 5 + 32)


def add_vat(amount):
    print(amount * 1.075)


celsius_to_fahrenheit(30)
add_vat(2000)

total = add_vat(2000)
print("total is", total)
print("two of them cost", total * 2)
PY
python3 printing.py || echo "exit status $?"

Line by line:

  • def celsius_to_fahrenheit(celsius): defines a function. def starts the definition, celsius_to_fahrenheit is its name, and celsius in brackets is a parameter: a name for the value the caller passes in. The colon and the indented lines below it are the function's body.
  • print(celsius * 9 / 5 + 32) is the body. It works out the Fahrenheit value and prints it.
  • add_vat does the same for a price: multiplying by 1.075 adds 7.5%.
  • celsius_to_fahrenheit(30) calls the function. The value 30 is an argument; inside the function, celsius holds 30 while the body runs.
  • total = add_vat(2000) tries to keep the answer in a variable so the program can use it.
  • The last two lines try to use that answer.

|| echo "exit status $?" after the command prints the exit status if Python stops with an error, so you can see the failure without your shell treating it as the end of the session.

Check it worked

The output starts with 86.0, 2150.0 and 2150.0: the third one is printed inside the function during total = add_vat(2000). Then comes total is None, followed by a traceback ending in TypeError: unsupported operand type(s) for *: 'NoneType' and 'int', and exit status 1.

The answer was printed, but total is None. A function that reaches the end of its body without a return statement gives back None, Python's value for "nothing". The printed 2150.0 went to the screen, not to your variable, and None * 2 is not a sum Python can do.

Step 2 · Return the value instead

Rewrite both functions so they hand their result back with return, and let the caller decide what to do with it:

Bash
cat > returning.py <<'PY'
def celsius_to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32


def add_vat(amount):
    return round(amount * 1.075, 2)


total = add_vat(2000)
print("total is", total)
print("two of them cost", total * 2)

hot = celsius_to_fahrenheit(30)
print(f"30 C is {hot} F")
print("hotter than 80 F?", hot > 80)
print("body temperature:", round(celsius_to_fahrenheit(37.5), 1))
PY
python3 returning.py

What changed:

  • return celsius * 9 / 5 + 32 works out the value and sends it back to the caller. The function stops at return; any line after it in the body would never run.
  • return round(amount * 1.075, 2) rounds to two decimal places before returning, because prices have two. round is itself a function that returns a value, which is why you can use its result directly.
  • total = add_vat(2000) now stores 2150.0, so total * 2 works.
  • hot > 80 compares the returned value with a limit, something the print-only version could never do.
  • round(celsius_to_fahrenheit(37.5), 1) passes one function's result straight into another. Python runs the inner call first, then hands its answer to round.

Nothing prints from inside the functions any more. Printing is now the caller's choice, so the same function serves a script that shows the answer, a test that checks it and a program that adds it to a total.

Check it worked

The output is:

Text
total is 2150.0
two of them cost 4300.0
30 C is 86.0 F
hotter than 80 F? True
body temperature: 99.5

There is no traceback, and each value appears once, printed by the caller.

Step 3 · Give parameters defaults and call them by name

A VAT calculator that only knows one rate is too rigid, but making every caller type the rate is tedious. A default value gives a parameter a value it uses when the caller leaves it out:

Bash
cat > defaults.py <<'PY'
def add_vat(amount, rate=0.075):
    return round(amount * (1 + rate), 2)


print(add_vat(2000))
print(add_vat(2000, 0.2))
print(add_vat(2000, rate=0.16))
print(add_vat(rate=0.15, amount=2000))
print(add_vat(0.075, 2000))
print(add_vat())
PY
python3 defaults.py || echo "exit status $?"
  • rate=0.075 in the definition is the default. Parameters with defaults must come after the ones without.
  • add_vat(2000) passes only the amount, so rate is 0.075.
  • add_vat(2000, 0.2) passes both by position: first value to the first parameter, second to the second.
  • add_vat(2000, rate=0.16) passes the rate as a keyword argument, by name. The call now says what 0.16 is, which helps whoever reads it later.
  • add_vat(rate=0.15, amount=2000) names both, so the order no longer matters.
  • add_vat(0.075, 2000) is a deliberate mistake: the arguments are swapped, so Python treats 0.075 as the amount and 2000 as the rate.
  • add_vat() leaves out amount, which has no default.

Check it worked

The first four lines are 2150.0, 2400.0, 2320.0 and 2300.0. The fifth is 150.07, a wrong answer with no error: Python cannot tell that you swapped the values, which is the best argument for keyword arguments when a function takes several numbers. The script then stops with TypeError: add_vat() missing 1 required positional argument: 'amount' and exit status 1.

Step 4 · Return more than one value

Sometimes you have a price that already includes VAT and want both parts back: the price before VAT and the VAT itself. A function can return several values separated by commas. Python packs them into a tuple, a fixed-length sequence, and the caller can unpack it into separate variables:

Bash
cat > tuples.py <<'PY'
def split_vat(gross, rate=0.075):
    net = round(gross / (1 + rate), 2)
    vat = round(gross - net, 2)
    return net, vat


result = split_vat(2150)
print(result)
print(type(result))

net, vat = split_vat(2150)
print("before VAT:", net)
print("VAT:", vat)

_, vat_at_20 = split_vat(240, rate=0.2)
print("VAT at 20%:", vat_at_20)
PY
python3 tuples.py
  • net = round(gross / (1 + rate), 2) divides out the VAT. Dividing by 1.075 undoes multiplying by 1.075.
  • vat = round(gross - net, 2) is what is left.
  • return net, vat returns both, packed into one tuple.
  • net, vat = split_vat(2150) unpacks the tuple: the first value goes into net, the second into vat. The number of names on the left must match the number of values, or Python raises ValueError.
  • _, vat_at_20 = ... uses _, a conventional name for "I do not need this one".

Rounding with floats is fine for learning. Real money code usually stores amounts as whole numbers of the smallest unit (kobo, pesewas, cents) or uses the decimal module, for reasons the tutorial on values and types in Python shows.

Check it worked

The output is:

Text
(2000.0, 150.0)
<class 'tuple'>
before VAT: 2000.0
VAT: 150.0
VAT at 20%: 40.0

The brackets in the first line show the tuple the function returned.

Step 5 · See which variables a function can use

Every call to a function gets its own private set of variables, called its local scope. A variable created inside a function exists only while that call runs. Variables created at the top level of the file are global, and a function can read them. Try both:

Bash
cat > scope.py <<'PY'
rate = 0.075


def add_vat(amount):
    total = round(amount * (1 + rate), 2)
    return total


print(add_vat(1000))
print(total)
PY
python3 scope.py || echo "exit status $?"
  • rate = 0.075 is global. add_vat reads it, which works.
  • total is created inside add_vat, so it is local. When the call ends, it is gone.
  • print(total) at the top level looks for a total that no longer exists.

Reading a global works, but changing one from inside a function does not work the way beginners expect. This version tries to count how many times the function has run:

Bash
cat > counting.py <<'PY'
calls = 0


def add_vat_and_count(amount):
    calls = calls + 1
    return round(amount * 1.075, 2)


print(add_vat_and_count(1000))
PY
python3 counting.py || echo "exit status $?"

Because the function assigns to calls, Python decides when it reads the file that calls is a local variable for the whole function body. The right-hand side, calls + 1, then tries to read that local variable before anything has been stored in it.

The fix that keeps functions easy to reason about is the one from this whole tutorial: pass the value in and return the new one.

Bash
cat > counting_fixed.py <<'PY'
def add_vat_and_count(amount, calls):
    return round(amount * 1.075, 2), calls + 1


calls = 0
price, calls = add_vat_and_count(1000, calls)
price, calls = add_vat_and_count(500, calls)
print(price, calls)
PY
python3 counting_fixed.py

Python also has a global statement that lets a function change a global variable. It works, but then any function anywhere can change that value, and a bug in one place shows up somewhere else. Passing in and returning keeps every change visible in the line that calls the function.

Check it worked

scope.py prints 1075.0, then stops with a traceback ending in NameError: name 'total' is not defined and exit status 1.

counting.py stops with UnboundLocalError: cannot access local variable 'calls' where it is not associated with a value and exit status 1. That wording is from Python 3.11 and later; older versions say something like local variable 'calls' referenced before assignment. It prints no price, because the error happens on the first line of the body.

counting_fixed.py prints 537.5 2: the price from the second call and a count of two calls.

Step 6 · Document the functions with docstrings

Collect the four tools in one file. Each function starts with a docstring: a string on the first line of the body that says what the function does. Python stores it with the function, and help() shows it:

Bash
cat > toolkit.py <<'PY'
"""Small helpers for temperatures and VAT."""


def celsius_to_fahrenheit(celsius):
    """Return the Fahrenheit value of a Celsius temperature."""
    return celsius * 9 / 5 + 32


def fahrenheit_to_celsius(fahrenheit):
    """Return the Celsius value of a Fahrenheit temperature."""
    return (fahrenheit - 32) * 5 / 9


def add_vat(amount, rate=0.075):
    """Return amount with VAT added, rounded to 2 decimal places.

    rate is a fraction: 0.075 means 7.5%.
    """
    return round(amount * (1 + rate), 2)


def split_vat(gross, rate=0.075):
    """Split a price that includes VAT into (net, vat), rounded to 2 places."""
    net = round(gross / (1 + rate), 2)
    return net, round(gross - net, 2)
PY
python3 -c 'import toolkit; help(toolkit.add_vat)'
  • The string at the very top of the file is the module's docstring, describing the file as a whole.
  • Each function's docstring sits on the line straight after def, inside triple quotes so it can span several lines. Start it with a verb that says what the function returns: "Return the ...".
  • A longer docstring has a one-line summary, a blank line, then details such as what a parameter means.
  • python3 -c '...' runs the Python code in quotes. import toolkit loads toolkit.py from the current folder, and help(toolkit.add_vat) shows the function's name, parameters and docstring.

The file has no code at the top level, only definitions, so importing it runs nothing except the def statements. That is what makes it reusable.

Check it worked

The help text starts with Help on function add_vat in module toolkit:, then shows add_vat(amount, rate=0.075) followed by your docstring, indented. In a terminal, help usually opens in a pager, a full-screen viewer, whether you call it with python3 -c or from the REPL: press q to leave it. To print it straight to the terminal instead, pipe it through cat: python3 -c 'import toolkit; help(toolkit.add_vat)' | cat.

Step 7 · Call and combine the functions in the REPL

Start the REPL from the functions-demo folder by typing python3 on its own. Import the four functions and use them together. Type each line after >>>:

Text
>>> from toolkit import celsius_to_fahrenheit, fahrenheit_to_celsius, add_vat, split_vat
>>> celsius_to_fahrenheit(100)
212.0
>>> fahrenheit_to_celsius(celsius_to_fahrenheit(37))
37.0
>>> add_vat(1500) + add_vat(2000)
3762.5
>>> split_vat(add_vat(2000))
(2000.0, 150.0)
>>> net, vat = split_vat(add_vat(500, rate=0.2), rate=0.2)
>>> vat
100.0
>>> exit()

Every result is a value you can feed into the next call: the Fahrenheit value goes back through the reverse converter, two VAT-inclusive prices add up, and split_vat undoes add_vat. None of that is possible with functions that only print.

Save the same checks as a script with assert statements. assert does nothing when its condition is true and stops the program with AssertionError when it is false, so the script checks your functions every time you run it:

Bash
cat > check_toolkit.py <<'PY'
from toolkit import celsius_to_fahrenheit, fahrenheit_to_celsius, add_vat, split_vat

assert celsius_to_fahrenheit(100) == 212
assert fahrenheit_to_celsius(212) == 100
assert fahrenheit_to_celsius(celsius_to_fahrenheit(37)) == 37
assert add_vat(2000) == 2150
assert add_vat(2000, rate=0.2) == 2400
assert split_vat(add_vat(2000)) == (2000, 150)
assert split_vat(add_vat(500, rate=0.2), rate=0.2) == (500, 100)

basket = [1500, 2000, 4500]
total = 0
for price in basket:
    total = total + add_vat(price)
print("basket with VAT:", total)
print("all checks passed")
PY
python3 check_toolkit.py

The loop adds up a basket of prices, each with VAT, using the returned values. 212.0 == 212 is True in Python, so comparing a float result with a whole number is fine here.

Check it worked

The REPL shows the values listed above. The script prints basket with VAT: 8600.0 and then all checks passed. To see an assertion fail, change 9 / 5 to 9 / 4 in toolkit.py, run python3 check_toolkit.py again, and read the AssertionError line, then change it back.

When you have finished, delete the demo folder:

Bash
cd ~
rm -rf ~/functions-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.