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.
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.
Words you will see in this lesson
Six words. The rest of the lesson uses only these.
| Word | What it means |
|---|---|
| Function | A named block of code you can run again and again |
| Parameter | A slot in the def line that waits for a value, such as price |
| Argument | The real value you put in the slot when you call, such as 19.50 |
| Call | Running a function by writing its name with brackets |
| return | Hand a result back to the line that called the function |
| Module | A 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.
| Situation | Formula pasted in 3 places | One function called from 3 places |
|---|---|---|
| The rule changes | Find and edit all three copies | Edit the one function |
| You miss a copy | The report and the invoice disagree | Not possible, they share the code |
| A new script needs it | Paste it a fourth time | Import 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.
| Step | What Python does | State |
|---|---|---|
| 1. Call | Pauses the calling line and starts the function | Nothing is stored yet |
| 2. Fill the slots | Puts each argument in its parameter | price = 19.50, qty = 4 |
| 3. Run the body | Works through the indented lines | price * qty is 78.0 |
| 4. Return | Sends 78.0 back and forgets the slots | The 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.
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.
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.
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.
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.
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.
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 definedThe 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.
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.
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.
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.
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.
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.
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 value | Safe? | Why |
|---|---|---|
| 0, 1.5, True | Yes | Numbers cannot change in place |
| "paid" | Yes | Text cannot change in place |
| None | Yes | The usual placeholder for a list or dict |
| [] or {} | No | One 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.
- Flatten Nested ListsInterview-style drill: Flatten arbitrarily nested lists without splitting strings.Studiobeginnerpython10 min
- Extract all email addresses from a nested payloadInterview-style drill: Given an arbitrarily nested dict/list structure, collect every value that looks like an email address.Studiointermediatepython15 minLocked
- Flatten a directory listing into pathsInterview-style drill: Given a nested dict representing folders and files, return every full file path.Studiointermediatepython15 minLocked