Cohort 4Register

PART 1 · PYTHON FROM ZERO · LESSON 14

Functions: reusable steps

FreeLesson 16 of 78

A function is a named recipe. Write the steps once, then run them on any input by calling the name.

DEFINE ONCE, CALL MANY TIMESPYTHON 3.12
def add_gst(amount, rate=0.18):
    """Return the amount with GST added."""
    total = amount * (1 + rate)
    return round(total, 2)

print(add_gst(1000))              # uses the default rate
print(add_gst(1000, 0.05))        # overrides it
print(add_gst(rate=0.12, amount=500))   # by name, any order

Output

1180.0
1050.0
560.0
PRINT VS RETURNPYTHON 3.12
def total_print(a, b):
    print(a + b)      # shows it, returns nothing

def total_return(a, b):
    return a + b            # gives the answer back

x = total_print(2, 3)
y = total_return(2, 3)
print("x is", x, "| y is", y)

Output

5
x is None | y is 5

total_print showed 5 but returned nothing, so x is None. If you need to use the answer later, return it.

VARIABLES INSIDE STAY INSIDEPYTHON 3.12
def double(n):
    result = n * 2    # only exists in here
    return result

print(double(21))
print(result)               # not visible outside

Output

42
NameError: name 'result' is not defined

Each call gets its own fresh set of local variables, which disappear when the function returns.

SMALL FUNCTIONS THAT BUILD ON EACH OTHERPYTHON 3.12
def is_delivered(status):
    return status.strip().lower() == "delivered"

def delivered_total(rows):
    total = 0
    for status, amount in rows:
        if is_delivered(status):    # a function in a function
            total += amount
    return total

rows = [("Delivered", 1198), ("cancelled", 1999), (" delivered ", 796)]
print(delivered_total(rows))

Output

1994
WordMeaning
ParameterThe name in the definition: amount in def add_gst(amount)
ArgumentThe value you pass when calling: 1000 in add_gst(1000)
Return valueWhat the call gives back. No return statement means None
Default valueUsed when the caller leaves that argument out: rate=0.18
DocstringThe text in triple quotes right under def; shown by help(add_gst)

Try it yourself before moving on

  1. Write is_even(n) that returns True or False.
  2. Write to_rupees(1198) that returns "Rs 1,198.00".
  3. Give a function a default currency of "INR" and call it with and without it.