Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python functions: define units, validate input and return a result

Last updated: 30 Sept 20264 min read
tutorial
BeginnerBy AITrove Editorial

A Python function defines a callable operation with its own local names and a stated argument/result contract.

Download Python source kit

Operation contract

The package-cost function accepts a nonnegative integer quantity and an integer minor-unit price, then returns an integer total. It rejects bool even though bool is an int subclass, because a boolean is not a quantity in this input format. Keyword-only unit_minor makes the price unit visible at a call site and avoids accidentally swapping two numeric fields.

Failure and ownership boundary

An annotation documents intent; it does not reject bad runtime input automatically. Validation belongs at the boundary whose input is untrusted. Printing a total is also different from returning it: the caller needs a returned value to compose calculations or test it without intercepting output. Python function arguments: avoid shared mutable defaults and Python input exercise: accept an explicit integer grammar cover the next layer.

Working program

python
def package_cost(quantity: int, *, unit_minor: int) -> int:
    if type(quantity) is not int or type(unit_minor) is not int:
        raise TypeError("integer amounts required")
    if quantity < 0 or unit_minor < 0:
        raise ValueError("negative quantity or price")
    return quantity * unit_minor

print(package_cost(3, unit_minor=125))
try:
    package_cost(True, unit_minor=125)
except TypeError:
    print("boolean quantity rejected")

Output

Output
375
boolean quantity rejected

Costs and limits

Local validation is fixed work for these bounded inputs. Integer multiplication grows with operand digits; apply domain bounds before accepting arbitrarily large textual numbers.

Common Mistakes

  • Annotations are not runtime validators.
  • Returning a value is different from printing it.

Connected lessons

Python function arguments: avoid shared mutable defaults, Python input exercise: accept an explicit integer grammar, Methods and objects.

Follow the related contract

Python lambda functions: one expression and the same closure rules, Python map, filter and reduce: iterator timing and reduction identity.

Check the next state boundary

Python first-class functions: dispatch through an explicit operation registry.

python
python-functions
Storage details