bhylu.com

Advertisements

Python Functions

A function gives a named operation inputs and returns a result. Use it to separate a calculation from the interface that displays or stores it.

Understand the idea

def creates the function. Parameters receive argument values when it is called, and return sends a value back to the caller. A function without an explicit return produces None. Keep a small function focused on a clear contract so you can test valid inputs, boundaries, and failures independently.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

def total_cents(unit_cents, quantity):
    return unit_cents * quantity

amount = total_cents(450, 3)
print(amount)

Read the result

The result is 1350. The function returns a number; print displays it afterward.

Try one change

Add validation for a negative quantity and decide which exception should describe that invalid input.