Lesson 2 of 5 in this module

8/43 in track

Functions, modules & imports

python10 min

Overview

A pipeline repeats the same cleaning and checking steps. Put those steps in functions, then place shared functions in modules that other jobs can import.

On this page8 sections

What you will do

A shop works out the same thing for every order line: price times quantity. If you type that sum again and again, you will make a typing mistake sooner or later.

A function lets you write the steps once, give them a name, and use that name wherever you need the answer.

What is a function, in the smallest example?

Here is a function with two slots, price and qty. It multiplies them and hands the answer back. Predict the two lines it prints.

PythonOne recipe, two calls
def subtotal(price, qty):
    return price * qty

print(subtotal(19.50, 4))
print(subtotal(250, 2))
78.0
500
  • def starts the recipe and gives it a name, subtotal.
  • price and qty are slots. They are empty until someone calls the function.
  • return price * qty says what comes back out.
  • subtotal(19.50, 4) is the call. It fills the slots with 19.50 and 4 and runs the recipe.

Nothing runs when Python reads the def lines. The body only runs when a call arrives.

A function call in four steps: the call subtotal(19.50, 4), the slots price and qty filled with 19.50 and 4, the body price times qty, and the returned value 78.0 going back to the line that made the call
Defining a function writes the recipe once. Each call fills the slots with real values, runs the body and sends one value back to the line that called it.

Words you will see in this lesson

Six words. The rest of the lesson uses only these.

WordWhat it means
FunctionA named block of code you can run again and again
ParameterA slot in the def line that waits for a value, such as price
ArgumentThe real value you put in the slot when you call, such as 19.50
CallRunning a function by writing its name with brackets
returnHand a result back to the line that called the function
ModuleA Python file whose functions other files can import

Why this skill

Pipelines repeat the same small jobs on thousands of rows: clean a name, convert a currency, check a status. Each job is a function.

What goes wrong when you copy and paste a formula?

Suppose the subtotal sum is pasted into the ingestion script, the daily report and the invoice script. Then the shop adds a rule, and you must find every copy.

Write the rule once. Every caller gets the fix at the same time.

SituationFormula pasted in 3 placesOne function called from 3 places
The rule changesFind and edit all three copiesEdit the one function
You miss a copyThe report and the invoice disagreeNot possible, they share the code
A new script needs itPaste it a fourth timeImport it and call it

A function is a rule with a name. Change the rule in one place and every caller follows.

Why are functions easy to test?

A function takes values in and gives a value out, so you can try it alone. Feed it 19.50 and 4 and check that you get 78.0, with no file or database involved.

When a total looks wrong, you test the one function that makes it instead of reading a 500-line script.

How the code works

Three ideas carry the whole lesson: what a call does, the difference between print and return, and where a function's own variables live.

What happens when you call a function?

Python runs four steps, always in this order. The table follows the call subtotal(19.50, 4).

The slots exist only while the function runs.

StepWhat Python doesState
1. CallPauses the calling line and starts the functionNothing is stored yet
2. Fill the slotsPuts each argument in its parameterprice = 19.50, qty = 4
3. Run the bodyWorks through the indented linesprice * qty is 78.0
4. ReturnSends 78.0 back and forgets the slotsThe call is replaced by 78.0

Because the call is replaced by its value, you can store it, print it or use it in a sum. Predict the second line this program prints.

PythonUsing the returned value
def subtotal(price, qty):
    return price * qty

result = subtotal(19.50, 4)
print("Subtotal:", result)
print("With GST:", result * 1.05)
Subtotal: 78.0
With GST: 81.9

result * 1.05 is 78.0 * 1.05, because result holds the value that came back.

What is the difference between print and return?

print shows text on the screen for a person. return sends a value back to the code that called the function. A function that only prints gives back nothing, and Python calls that nothing None.

Both functions below work out the same sum. Predict what a and b hold.

PythonPrinting is not the same as returning
def show_subtotal(price, qty):
    print(price * qty)

def get_subtotal(price, qty):
    return price * qty

a = show_subtotal(19.50, 4)
b = get_subtotal(19.50, 4)
print("a is", a)
print("b is", b)
78.0
a is None
b is 78.0

The first line, 78.0, was printed by show_subtotal while it ran. It never reached a, so a is None.

RememberReturn the value, print it later

If other code needs the answer, use return. print is for humans reading the screen. A function that prints but does not return breaks any sum you try to do with its result.

Can a parameter have a default value?

Yes. Write the default in the def line with an equals sign. A caller who skips that argument gets the default.

PythonA discount that defaults to zero
def subtotal(price, qty, discount=0):
    return price * qty * (1 - discount)

print(subtotal(19.50, 4))
print(subtotal(19.50, 4, 0.10))
print(subtotal(price=19.50, qty=4, discount=0.10))
78.0
70.2
70.2

The first call skipped discount, so it used 0 and kept the full 78.0. The second call passed 0.10, which takes 10 percent off.

The third call names each argument. Naming is safer when a function has many slots, because the order no longer matters. Slots with defaults must come after the slots without.

How does a function accept any number of values?

Put a star in front of one parameter. Python then collects every value you pass into a single tuple, which is a fixed list. This is how total_of can take 3 amounts today and 30 tomorrow.

PythonA star collects all the values
def total_of(*amounts):
    print("received:", amounts)
    return sum(amounts)

print(total_of(10, 20, 5))
print(total_of(99))
print(total_of())
received: (10, 20, 5)
35
received: (99,)
99
received: ()
0

sum adds up everything in the tuple. With no values at all the tuple is empty and the sum is 0.

Where do a function's variables live?

A variable made inside a function belongs to that call. It disappears when the function returns, so code outside cannot see it. Predict what the last line does.

Pythonline exists only inside the function
def subtotal(price, qty):
    line = price * qty
    return line

print(subtotal(19.50, 4))
print(line)
78.0
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(line)
          ^^^^
NameError: name 'line' is not defined

The first print worked, because return carried the value out. The second failed, because line was left behind inside the function.

This is a feature. Two functions can both use a variable called total and never disturb each other.

How do you reuse a function from another file?

A module is a Python file full of functions. The import line brings one of them into your file, so you do not copy it.

PythonImport a ready-made function
from math import ceil

rows = 23
page_size = 10
print(rows / page_size)
print(ceil(rows / page_size))
2.3
3

23 rows at 10 per page need 3 pages, not 2.3. ceil rounds up, and it lives in Python's built-in math module.

Your own files work the same way. If you save subtotal in a file called order_math.py, then from order_math import subtotal gives any other script the same function.

RememberType hints are optional labels

You may see def subtotal(price: float, qty: int) -> float. The extra words say what kind of value is expected. Python ignores them when running, so subtotal("19.50", 4) would still run and repeat the text 4 times. Hints help readers and checking tools.

Worked examples

How do small functions build an invoice?

A finance script needs a subtotal, then tax on it, then a rounded total. Each step is its own function, and a third function chains them. Predict the last two numbers.

PythonThree small functions, one chain
def subtotal(price, qty):
    return price * qty

def add_tax(amount, rate):
    return amount * (1 + rate)

def invoice_total(price, qty, rate):
    return round(add_tax(subtotal(price, qty), rate), 2)

print(subtotal(19.50, 4))
print(add_tax(78.0, 0.05))
print(invoice_total(19.50, 4, 0.05))
78.0
81.9
81.9

Read invoice_total from the inside out. subtotal gives 78.0, add_tax turns it into 81.9, and round keeps two decimals.

If the tax rule changes, you edit add_tax and nothing else. If a total looks wrong, you test the three small functions one at a time.

What does a missing argument look like?

Call a function with fewer values than it has slots and Python tells you which slot was left empty.

PythonOne argument too few
def subtotal(price, qty):
    return price * qty

print(subtotal(19.50))
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(subtotal(19.50))
          ~~~~~~~~^^^^^^^
TypeError: subtotal() missing 1 required positional argument: 'qty'

Read the last line first. It names the function, says how many values are missing, and names the slot, qty.

Common beginner questions

Do I have to write return?

No, but without it the function gives back None. If you want the answer in a variable or a sum, write return.

What is the difference between a parameter and an argument?

A parameter is the slot in the def line, such as price. An argument is the real value you pass in the call, such as 19.50. People mix the two words up all the time, and it rarely matters.

Why did my function print the answer but my variable holds None?

Because the function used print and not return. print shows the value but does not send it back, so the variable receives None.

When should I write a function instead of a few lines?

When you use the same steps in more than one place, when you want to test the steps alone, or when a name would make the code easier to read. A helper used once that only renames one built-in adds noise.

What comes next

You can now name a piece of logic, call it with different values and get an answer back. The next lesson, Strings and text, uses functions you did not write, such as strip and split, to clean the raw text that files and APIs send.

Practice

In the exercise, define total_of(*amounts) that sums every number passed to it. Call it with 10, 20 and 5, assign the result to result, and print it. The answer is 35.

Going further: the default argument that remembers

A default value is evaluated once, when the function is defined, not every time it is called. For numbers and text that never matters. For a list or a dictionary it does, because the same object is reused on every call, and a function can seem to remember things between calls.

This function is meant to start a fresh list of failed order ids each time. Predict the three printed lists.

PythonA mutable default
def collect(order_id, failed=[]):
    failed.append(order_id)
    return failed

print(collect("ORD-1"))
print(collect("ORD-2"))
print(collect("ORD-3"))
['ORD-1']
['ORD-1', 'ORD-2']
['ORD-1', 'ORD-2', 'ORD-3']

Each call added to the same list, so the second and third calls returned the earlier ids too. The usual fix is to use None as the default and make the list inside the function.

PythonThe fix: None, then build the list inside
def collect(order_id, failed=None):
    if failed is None:
        failed = []
    failed.append(order_id)
    return failed

print(collect("ORD-1"))
print(collect("ORD-2"))
print(collect("ORD-3"))
['ORD-1']
['ORD-2']
['ORD-3']

Which defaults are safe.

Default valueSafe?Why
0, 1.5, TrueYesNumbers cannot change in place
"paid"YesText cannot change in place
NoneYesThe usual placeholder for a list or dict
[] or {}NoOne object is shared by every call

Try a new scenario

A function def add_tag(tag, tags={}) stores tags[tag] = True and returns tags. Two different orders call it once each. What does the second order see, and how do you repair it?

Work it out, then open the answer

The second order sees the first order's tag too, because both calls received the same dictionary object. The repair is the same as for the list: use tags=None, and write if tags is None: tags = {} as the first line of the function.

Why does Python build the default only once?

The def line runs once, when the function is created, and the default is built right then and stored with the function. Calls reuse it. This is a design choice that keeps calls cheap, and it is why a change made inside the function to a default list stays after the call ends.

Close the lesson and explain it

Without scrolling up, explain why a list as a default value can make a function behave differently on its second call, and write the safer version from memory.

Practicals · load into the editor

After you read the theory, run these in the pane on the right. They execute in this tab, no cluster.

Finished this lesson?

Mark it as read when you could explain it to someone else.

Practice this idea

Each page shows the idea moving, then lists problems from easiest. Open one now, or come back when you finish the lesson.

Practice this

Same ideas as interview drills. These challenges open in the studio with a dataset and tests already set up.

Rate:
Was this useful?