Skip to content
  • Official
  • Beginner
  • English
  • 12 steps · 2 quizzes

Python Functions: Practice Exercises with Solutions

Python functions exercises with worked solutions: watch each call open its own box, then practise arguments, return values, defaults and scope.

  • Free
  • No account needed
  • Stop any time, pick up where you left off
Workshopy.io

WorkshopyOfficial

78 lessons · used by 2 teachers

For teachers

Teaching this? Run it live with your class.

  • Students join with a code — no accounts
  • See who’s done and who’s stuck, step by step
  • It’s your copy — change anything before class

Sign in to copy it to your workspace. It’s free.

Your path

12 steps · 2 quizzes · open any step, or read it here

  1. Python functions exercises: what you'll practiseStart hereIn this lesson you practise Python functions with exercises: you define functions, pass them arguments, return values and see which names each function can reach.InteractiveHands-on
    Read this step

    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:

    • define a function with def and call it as many times as you like
    • pass arguments into parameters, by position and by name, and give parameters default values
    • hand a result back with return, and see why print is not the same
    • see which names a function can reach (scope), and what happens when one function calls another
    • predict what a function does to a list you give it

    It 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.

  2. def and calling: the body runs only when you call itA 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.InteractiveHands-on
    Read this step

    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:

    1. The def line runs nothing in the body. It only teaches Python a new name, greet. The indented lines wait.
    2. Each call runs the body again, from its first line, with fresh values. Call it twice and the body runs twice.

    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.

  3. Parameters and arguments: values go in by positionIn def invoiceline(item, qty, unitprice): the names in brackets are parameters: empty slots the function's body works with. In a call, invoiceline("Cables", 3, 4.5), the values in brackets are arguments: what goes into those slots this time.InteractiveHands-on
    Read this step

    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.

  4. return: hand a value back to the callerMost useful functions work something out and give it back. That is what return doesInteractiveHands-on
    Read this step

    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.

  5. print is not return: the None you get backprint 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.InteractiveHands-on
    Read this step

    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.

  6. Check: def, arguments and returnFour questions on the first half.Quiz · 4 questions
    Read the questions

    Four questions on the first half.

    Question 1. What happens when Python runs a `def` line?

    • The function's body runs once
    • The function gets its name; its body runs later, when it is called
    • Python checks every line of the body for mistakes and runs the first one
    • Nothing at all until the program ends

    Question 2. `def total(price, qty):` is called as `total(10)`. What happens?

    • qty is set to 0
    • qty is set to 10 too
    • Python stops with a TypeError: a required argument is missing
    • It returns None

    Question 3. What does a function give back when it has no `return` line?

    • 0
    • The last value it printed
    • None
    • An empty string

    Question 4. Which line hands 10 back to the code that called the function?

    • print(10)
    • return 10
    • result = 10
    • 10
  7. Default values and keyword argumentsA parameter can have a default value, written in the def line with =. A call that leaves the argument out gets the defaultInteractiveHands-on
    Read this step

    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.

  8. Local scope: each call has its own boxA 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.InteractiveHands-on
    Read this step

    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.

  9. Global names: read them, don't assign themNames 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.InteractiveHands-on
    Read this step

    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.

  10. Functions that call functions: boxes stack upA 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.InteractiveHands-on
    Read this step

    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.

Comments

You’ll sign in with Google before it’s posted.Comments are public — don’t name your students.
0 / 1,500

No comments yet. Be the first to say how it went.

Using it

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.

Versions

  1. 1

    Version 1Current

    · First published

Copies are made from the current version. A copy you already have doesn’t change.

More from Workshopy

All 78 lessons
All 13 Programming lessons