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.
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 orderOutput
1180.0 1050.0 560.0
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.
def double(n):
result = n * 2 # only exists in here
return result
print(double(21))
print(result) # not visible outsideOutput
42 NameError: name 'result' is not defined
Each call gets its own fresh set of local variables, which disappear when the function returns.
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
| Word | Meaning |
|---|---|
| Parameter | The name in the definition: amount in def add_gst(amount) |
| Argument | The value you pass when calling: 1000 in add_gst(1000) |
| Return value | What the call gives back. No return statement means None |
| Default value | Used when the caller leaves that argument out: rate=0.18 |
| Docstring | The text in triple quotes right under def; shown by help(add_gst) |
Try it yourself before moving on
- Write is_even(n) that returns True or False.
- Write to_rupees(1198) that returns "Rs 1,198.00".
- Give a function a default currency of "INR" and call it with and without it.