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:
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.defstarts the definition,celsius_to_fahrenheitis its name, andcelsiusin 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_vatdoes the same for a price: multiplying by1.075adds 7.5%.celsius_to_fahrenheit(30)calls the function. The value30is an argument; inside the function,celsiusholds30while 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:
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.pyWhat changed:
return celsius * 9 / 5 + 32works out the value and sends it back to the caller. The function stops atreturn; 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.roundis itself a function that returns a value, which is why you can use its result directly.total = add_vat(2000)now stores2150.0, sototal * 2works.hot > 80compares 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 toround.
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:
total is 2150.0
two of them cost 4300.0
30 C is 86.0 F
hotter than 80 F? True
body temperature: 99.5There 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:
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.075in the definition is the default. Parameters with defaults must come after the ones without.add_vat(2000)passes only the amount, sorateis0.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 what0.16is, 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 treats0.075as the amount and2000as the rate.add_vat()leaves outamount, 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:
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.pynet = round(gross / (1 + rate), 2)divides out the VAT. Dividing by1.075undoes multiplying by1.075.vat = round(gross - net, 2)is what is left.return net, vatreturns both, packed into one tuple.net, vat = split_vat(2150)unpacks the tuple: the first value goes intonet, the second intovat. The number of names on the left must match the number of values, or Python raisesValueError._, 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:
(2000.0, 150.0)
<class 'tuple'>
before VAT: 2000.0
VAT: 150.0
VAT at 20%: 40.0The 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:
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.075is global.add_vatreads it, which works.totalis created insideadd_vat, so it is local. When the call ends, it is gone.print(total)at the top level looks for atotalthat 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:
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.
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.pyPython 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:
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 toolkitloadstoolkit.pyfrom the current folder, andhelp(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 >>>:
>>> 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:
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.pyThe 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:
cd ~
rm -rf ~/functions-demoNext steps
- Use these ideas on a whole program: organise the budget tracker into functions.
- Find out what happens when a function changes a list you passed in: references and mutability.
- Move
toolkit.pyinto a package other scripts can import: split Python code into modules.
Part of these paths
Related tutorials
- Organise the budget tracker into functionsYou will split the fifty-line budget tracker into ask_for_expense, total_spent, total_by_category, print_summary and main, proving after every move that it still prints exactly the same summary.
- Why changing one list changed another: references and mutability in PythonYou will reproduce three classic Python bugs where a list changes behind your back, learn how names refer to objects and which types can change, and end with a script that proves all three bugs are fixed.
- Split Python code into modules and import themYou will turn one growing Python script into a main script, a converters module and a small package, import them three different ways, and know how Python finds each one.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials