Python Tutorial / Define Functions and Return Values

A function gives a processing step a name, receives inputs through parameters and returns a result. Returning a value differs from printing it; separating calculation from display makes the same logic reusable.

Name the parameters, arguments and result

A def statement names a function and defines its indented body. Parameters are the names in that definition; arguments are the actual values supplied by a call. Defining the function does not execute its body.

return ends the current call and provides its result. Reaching the end without a return value produces None. A calculation that only prints cannot supply its number to another calculation as conveniently as one that returns it.

For the relevant APIs and platform requirements, see Define Functions and Return Values documentation.

Run a function and reuse its results

Save the complete code below as functions.py in a separate practice folder, using UTF-8. Run python functions.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.

def total_with_fee(amount, fee):
    """Return the sum of the amount and fee."""
    return amount + fee

first = total_with_fee(8000, 500)
second = total_with_fee(3500, 0)
print(first, second)
print(first + second)

Expected output:

8500 3500
12000

Define the function’s responsibility

The sample assumes two numeric values that can be added. Whether negative amounts or fractional units are allowed is a separate contract. Validate data at a suitable boundary and state the assumptions of internal helpers rather than making every function handle every imaginable input.

Choose a name that describes the operation. Avoid growing one function to handle prompting, calculation and file storage together. A docstring should explain the result, required assumptions and relevant exceptions, rather than inventing behavior the implementation does not enforce.

Inspect call failures and missing results

  1. Change the fee from 500 to 1000 and verify that the first result becomes 9000.
  2. Temporarily replace return with print, inspect the value of first and then restore return.
  3. Try calling the function before its definition executes and inspect the missing-name error.

Local variables normally cannot be read directly outside their function call. Return the required value instead of relying on hidden external state. For TypeError caused by missing arguments, compare the definition with the call. The argument and default-value guide explains optional inputs.