Intro to Git — Snapshots, Branches & Sharing
WorkshopyOfficial10 stepsQuiz9 interactiveDiagram
gitversion controlbeginners
Python functions exercises with worked solutions: watch each call open its own box, then practise arguments, return values, defaults and scope.

WorkshopyOfficial
78 lessons · used by 2 teachers
Sign in to copy it to your workspace. It’s free.
12 steps · 2 quizzes · open any step, or read it here
In this lesson you practise Python functions with exercises: you define functions, pass them arguments, return values and see which names each function can reach. Every call is drawn as a box, so you can watch the values go in, the work happen and the result come out, instead of guessing.
Here is the whole idea in six lines. Press Play and watch the call add_vat(200, 0.2) open a box of its own, work out the tax inside it, and hand 240.0 back:
Interactive · How a function call works: arguments in, a value out — try it in the lesson
In this lesson you'll:
def and call it as many times as you likeprint is not the sameIt takes about 70 minutes. Press Step to run one line at a time, Back to go back, Play to watch it run. In the exercises you pick the missing pieces of real code and press Run tests: the results are what Python 3 really prints for your picks.
Takeaway: a call opens a box, the arguments go into its parameters, and return hands one value back.
A function is a block of code with a name. You write it once with def, and from then on you can call it by its name followed by brackets.
def greet(name):
print("Hello,", name)
Two things surprise people at first:
def line runs nothing in the body. It only teaches Python a new name, greet. The indented lines wait.And because def is a line like any other, it has to run before you call the function. Python reads from top to bottom: a call above the def meets a name that doesn't exist yet.
Try it: step through Define, then call and count how many times line 2 runs. Then pick Call before def and see where Python stops.
Interactive · Defining a function and calling it — try it in the lesson
Takeaway: def makes the function; only a call runs its body, once per call.
In def invoice_line(item, qty, unit_price): the names in brackets are parameters: empty slots the function's body works with. In a call, invoice_line("Cables", 3, 4.5), the values in brackets are arguments: what goes into those slots this time.
Python fills the slots by position: the first argument goes into the first parameter, the second into the second, and so on. It does not look at what the values mean. Swap two arguments and the function happily runs with the wrong values, until something fails.
| Call | item | qty | unit_price |
|---|---|---|---|
invoice_line("Cables", 3, 4.5) |
'Cables' |
3 |
4.5 |
invoice_line(3, "Cables", 4.5) |
3 |
'Cables' |
4.5 |
The number has to match too: three parameters need three arguments (later you'll see how a default value makes one optional).
Try it: run Arguments in order, then Two swapped and One missing. Watch the call's box: which value lands in which name?
Interactive · Arguments land in parameters by position — try it in the lesson
Now your turn. Pick the missing pieces, then press Run tests. Wrong picks are worth trying too: you see the real output or the real error Python gives.
Interactive · Practice: arguments go in by position — try it in the lesson
Takeaway: arguments fill parameters left to right, one each; order and count must match.
Most useful functions work something out and give it back. That is what return does:
def with_discount(price, percent):
cut = price * percent / 100
return price - cut
When Python reaches return, three things happen at once: the value after return is worked out, the call's box closes, and the call itself is replaced by that value where it was written. So a = with_discount(80, 25) becomes a = 60.0.
Because a call turns into a value, you can use it anywhere a value fits: in a sum, in an if, as the argument of another call.
meeting = hours_to_minutes(1.5) + 15
Try it: in Two discounts, stop on the step where the box shows returns 60.0, then press Step once more and watch the value land in a. In Use the result, see the call turn into 90.0 inside a sum.
Interactive · return hands one value back — try it in the lesson
Now write three small functions. The tests call each one and compare what comes back, the way an automated test does at work.
Interactive · Practice: functions that return a value — try it in the lesson
Takeaway: return ends the call and puts its value where the call was written.
print and return look alike in small examples, because both seem to "give a result". They do different jobs:
print(x) shows x on the screen, for a person to read. The program can't use what was printed.return x hands x to the code that called the function, so it can be stored, added, compared or passed on.A function that never reaches a return still gives something back: the special value None, which means "nothing". That is why x = add_print(2, 3) shows 5 on screen and then stores None in x.
return also ends the function. A return inside an if lets a function stop early, and the lines after it run only when it didn't:
def check_stock(count):
if count == 0:
return "Out of stock"
return "In stock: " + str(count)
Try it: in print or return, compare what lands in x and in y. In return ends it, see which lines run for 0 and which for 7.
Interactive · print shows a value, return hands it back — try it in the lesson
Takeaway: print is for people, return is for the program; no return means None.
Four questions on the first half.
Question 1. What happens when Python runs a `def` line?
Question 2. `def total(price, qty):` is called as `total(10)`. What happens?
Question 3. What does a function give back when it has no `return` line?
Question 4. Which line hands 10 back to the code that called the function?
A parameter can have a default value, written in the def line with =. A call that leaves the argument out gets the default:
def price_label(amount, currency="EUR", decimals=2):
return str(round(amount, decimals)) + " " + currency
price_label(7.456) gives '7.46 EUR', price_label(7.456, "USD") gives '7.46 USD'. Parameters without a default must come first in the def line.
To set a later parameter but keep an earlier default, name it: a keyword argument, decimals=1. With names, order doesn't matter: price_label(currency="GBP", amount=12) works. The one rule: once you name an argument, every argument after it must be named too.
Try it: in Defaults, read the call's box on each call: which values came from the call, which from the defaults? Then try Keywords in any order.
Interactive · Defaults fill in what the call leaves out — try it in the lesson
Now fill the calls and the def line:
Interactive · Practice: defaults and keyword arguments — try it in the lesson
Takeaway: a default makes a parameter optional; a keyword argument sets one by name.
A name you create inside a function, a parameter or a variable it assigns, is local: it lives in that call's box. When the call returns, the box closes and its names are gone. Code outside the function never sees them.
def monthly_cost(yearly):
months = 12
return yearly / months
cost = monthly_cost(600)
print(months) # NameError
This is a feature, not a limitation. Because every call has its own box, a function can use any names it likes without clashing with the rest of the program: a result inside double() and a result outside it are two different names in two different boxes.
Try it: run A local name to the end and watch where months lives. Then run Same name, two boxes: how many result names exist while double is working?
Interactive · Each call keeps its names in its own box — try it in the lesson
Predict first, then check. Draw the boxes if it helps:
Interactive · Practice: which box is a name in? — try it in the lesson
Takeaway: names made inside a function live in its call's box and vanish when it returns.
Names made at the top of the program live in the global box. A function can read a global name: if a name isn't in its own box, Python looks in the global box next.
rate = 0.2
def add_tax(price):
return price + price * rate # reads the global rate
Assigning is different. As soon as a function assigns to a name anywhere in its body (count = …), that name is local in every line of that function. So count = 1 inside a function makes a new local count and leaves the global one alone, and count = count + 1 fails: the local count has no value yet when the right side reads it.
Python has a global statement that lets a function assign to a global name, but code that uses it is hard to follow and to test. The usual fix is simpler: pass the value in, and return the new one.
def add_ticket(count):
return count + 1
count = add_ticket(count)
Try it: step through all four programs. In Assigning makes a local, look for two count names at once.
Interactive · Reading and assigning global names — try it in the lesson
Takeaway: a function may read global names; to change one, pass it in and return the new value.
A function can call another function. Each call opens its own box on top of the one that called it, and the caller waits on its line until the inner call returns. This pile of boxes is the call stack.
def subtotal(qty, unit):
return qty * unit
def with_shipping(qty, unit):
cost = subtotal(qty, unit)
if cost < 50:
cost = cost + 5
return cost
Notice that both functions have parameters called qty and unit: each box has its own, so they never clash. The last box opened is always the first to close, and its returned value goes to the box just below.
Splitting work this way is how real programs stay readable: subtotal does one thing, with_shipping builds on it, and each can be tested on its own.
Try it: press Step until three boxes are open. Which lines are marked waiting, and why?
Interactive · The call stack: a box on top of a box — try it in the lesson
Takeaway: each call stacks a new box; the newest box closes first and returns to the one below.
When you pass a list to a function, Python does not copy it. The parameter becomes a second name for the same list. So a function that changes the list, with append, remove or cart[0] = …, changes the caller's list too.
def add_item(cart, item):
cart.append(item)
my_cart = ["pen"]
add_item(my_cart, "paper")
print(my_cart) # ['pen', 'paper']
Assigning is different again. cart = [] inside the function doesn't empty anything: it points the local name cart at a new list, and the caller's list stays as it was.
Numbers and strings can't be changed in place, so for them this question never comes up: a function can only hand a new value back with return.
Try it: in both programs, watch the list 1 badge. When do two names point at the same list?
Interactive · A list passed in is the same list — try it in the lesson
Takeaway: a list passed in is the caller's own list; changing it changes theirs, assigning the name does not.
Time to put it together: a parameter or two, a calculation, and a return. Each task is a function you'd find in a reporting script. Pick the missing pieces and press Run tests; the tests are the kind a team runs on every change.
Before you pick, say out loud what each function should return for the first test. That habit, deciding the answer before running the code, is what makes exercises stick.
Interactive · Practice: write three functions — try it in the lesson
If you have Python on your computer, type one of the finished functions into a file, call it with your own values and print the result.
Takeaway: a good function takes what it needs as parameters and returns one clear result.
Work out what each program prints, then check. Run it in Python only after you've answered. A hint costs nothing, and a wrong answer costs nothing either.
def area(width, height):
return width * height
print(area(3, 4) + area(2, 5))
def shout(word):
print(word.upper())
x = shout("hi")
print(x)
def fee(amount, rate=0.1):
return amount * rate
print(fee(200) + fee(200, rate=0.5))
def total(prices):
s = 0
for p in prices:
s = s + p
return s
print(total([5, 10, 15]))
limit = 10
def check(x):
limit = 3
return x > limit
print(check(5), limit)
def order(item, qty=1): Which call stops with a TypeError?Six questions on the whole lesson.
Question 1. With `def remind(name, days=30):`, what is `days` in the call `remind("Ana")`?
Question 2. A function makes `total = 50` inside its body. After the call returns, what does `print(total)` at the top level do, if there is no global `total`?
Question 3. `count = 0` is global. A function runs `count = 5`, with no `global` line. What is the global `count` afterwards?
Question 4. `def add(cart): cart.append("ink")` is called as `add(my_cart)` with `my_cart = ["pen"]`. What is `my_cart` afterwards?
Question 5. For `def label(amount, currency="EUR"):`, which calls work? (pick all that apply)
Question 6. `with_shipping()` calls `subtotal()`. Which box closes first?
Workshopy shares this lesson under CC BY 4.0. Anyone may use and change it, with credit to you. Anyone can learn it here, free. A copy in your workspace is yours to change and run live; your students never need an account.
Version 1Current
· First published
Copies are made from the current version. A copy you already have doesn’t change.
WorkshopyOfficial10 stepsQuiz9 interactiveDiagram
gitversion controlbeginners
WorkshopyOfficial16 steps2 quizzes15 interactiveDiagram
workshopyproduct touronboarding
WorkshopyOfficial10 steps2 quizzes10 interactive
data-literacystatisticsmean and median
WorkshopyOfficial12 steps2 quizzes11 interactive
devopsregexregular expressions
WorkshopyOfficial12 steps2 quizzes11 interactive
gitpull requestscode review
WorkshopyOfficial11 steps2 quizzes11 interactive
devopsdockercontainers
Comments
No comments yet. Be the first to say how it went.