Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Functions

Functions 27 minA function is a reusable unit of instructions that you call with inputs and that can return a result.

A function is a reusable unit of instructions that you call with inputs and that can return a result.

Follow arguments, returned values, local names and shared objects, then combine functions into larger behavior.

Python / Follow the value

Print and return: follow one function call

Read each scene, then follow the next step when you are ready.

01 · Find the missing result

It calculated 120. Why did checkout stop?

Illustrated execution
Callercode that makes this call
bill = None

The call gave back None

after_voucher =None - 10TypeError

Python cannot subtract a number from None.

FUNCTION BOUNDARYadd_fee
1def add_fee(subtotal):2    total = subtotal + 203    print(total)
subtotal100parameter: input name
total120local result: 100 + 20
End of functionno return statement → returns None
Consoletext for the person reading
120

120 appeared here. It did not become the value of bill.

01

Look at the two results: 120 reached the console, but bill - 10 failed. That subtraction needs the fee-inclusive number to produce 110. Seeing 120 on screen proves the addition happened. We still need to find out what value was stored in bill.

1 / 7

Move at your own pace, or play the explanation. It pauses for your edit. The experiment below runs the program in Python.

Use the same rule with a new input

What changes when the subtotal is 200?

Start with the repaired version below. The fee is still 20 and the voucher is still 10. Work out what bill will receive, then predict what the final print will display. Run the program to check. You can select the original version afterwards to compare.

Read the program you are about to run
def add_fee(subtotal):
    total = subtotal + 20
    return total

bill = add_fee(200)
after_voucher = bill - 10
print(after_voucher)

Extend what already works

Show the total and preserve the return.

The starter already returns the correct number. Add the missing display inside add_fee, keeping its name, parameter, and returned result. The caller stays unchanged: it subtracts 10 and prints the final amount.

Think about the order: print displays text and execution continues. return ends the current call. An instruction placed after that return will not run in this call.

For subtotal 100120
110

The function prints the first line.
The caller prints the second.

For 200, expect 220 then 210.
your_function.pyEdit the function below
Checked with 100, 200, and 0.

Carry this question into the next program: what does the caller need back? When another calculation needs the result, return it. Print when you also want to inspect what happened. A message in the console does not supply a value to the next function.

Detailed reference, complete examples and extra practice

Read the complete explanation and examples here, or use the experiments above to inspect calls, returned values and shared state.

Functions

A function is a reusable unit of instructions that you call with inputs and that can return a result.

Follow arguments, returned values, local names and shared objects, then combine functions into larger behavior.

Before you begin: read an assignment such as subtotal = 100, add and subtract numbers, and run a simple print call.

This checkout adds a fixed ₹20 service fee, then subtracts a ₹10 voucher. A ₹100 subtotal should therefore become ₹110. We put the fee calculation in add_fee, a function: named instructions we can run with different inputs. Follow one call to see why displaying an answer is not enough to finish the bill.

Read the explanation

The function handles one part of checkout: adding the service fee. The code outside it handles the voucher and displays the final amount. Keeping those jobs separate lets us reuse the fee calculation with different subtotals.

def add_fee(subtotal) defines the function. Its indented lines are the body, which runs when we call add_fee(100). Defining the function alone does not perform the calculation.

def add_fee(subtotal):
    total = subtotal + 20
    print(total)
bill = add_fee(100)
after_voucher = bill - 10
print(after_voucher)

Start at bill = add_fee(100). Python evaluates the right-hand side before assigning bill. The code making this call is the caller. It supplies the argument 100. Inside the function, the parameter subtotal names that input. The body computes total = 120. This name is local: it belongs to this call, rather than becoming a new name in the calling code.

print(total) writes 120 to the console. Printing does not end the function or give bill a value. Execution continues to the end of the body. Because nothing explicitly returned a result, Python returns None. The caller now assigns bill = None.

None is a Python value, not the number zero. The next operation is None - 10, which raises TypeError: subtraction cannot use those two kinds of value. The program stops before its final print. Although 120 appeared in the console, the caller never received that number.

Replace the function's print with return total. This statement ends the call and supplies its value to the waiting caller:

def add_fee(subtotal):
    total = subtotal + 20
    return total
bill = add_fee(100)
after_voucher = bill - 10
print(after_voucher)

Now bill receives 120, and subtracting the voucher produces 110. Only 110 appears in the console: the function returned its number without printing, and the caller printed the final amount. For input 200, the corresponding values are 220 and 210.

A function can also print and return. The independent task asks for both the fee total and the final amount to be displayed. Keep the caller unchanged. Think about the order inside the function: once return executes, that call ends, so a print placed after it will never run.

More ways to supply and receive values

You have completed the print-and-return checkpoint. The rest of this lesson adds calling options, scope, and other function behaviors. Continue once you can repair the function independently; these later details are not needed to explain why its first version returned None.

For a bill splitter, a default argument lets a caller omit an optional input. In def split(bill, people, tip=10), leaving out tip uses 10. Arguments normally fill parameters from left to right. Supplying names, such as split(people=4, bill=800), makes the intended parameter explicit.

Sometimes a calculation produces two useful results. The next example returns them together in a tuple, an ordered group of values. The assignment each, extra = ... gives each returned item a name. You can revisit the collections lesson for more about tuples.

python

The string under the def line is a docstring. Editors and help(split) show it, so say what the function returns.

Follow the contract across two calls

The signature says how arguments bind to parameters; the contract adds what those values mean. For split, people must be a positive integer. Its result (share, left_over) promises whole-rupee shares plus the amount not allocated. For total 1100 and three people, 366 * 3 + 2 == 1100. The remainder is part of the answer, not a rounding mistake to hide.

Call evaluation proceeds in order: evaluate the supplied arguments, bind parameters, run the body, then use its returned value in the caller. An exception interrupts that path rather than producing an ordinary result. A default handles an omitted argument; split(100, 2, tip=0) supplies zero and must not be treated as if the caller omitted the tip.

Compose two small functions without printing between them: one computes a shipping charge from weight; another adds that returned charge to a subtotal. State the accepted weight range and the returned units. Then test the first function separately from the composition. If both small functions are right but the combined result is wrong, inspect their connecting values and units.

Count UPI payments

A shop app keeps a running count of payments. This is where scope matters: which names a function can see, and which ones it can change.

Nested boxes: Built-ins outside, then Global holding GST = 0.18, then Enclosing, then a green Local box for the current call; looking up GST checks Local, then Enclosing, then finds it in Global

A function can read a global such as GST when no nearer binding shadows it. A local name is not automatically visible in the caller; returning its value does not export the name itself. The tax rate here is illustrative:

What happens when you run this?
GST = 0.18

def tax(price):
    amount = price * GST     # reads the global GST: fine
    return amount

tax(500)
print(amount)

Now the count. Reading a global is fine, so this looks safe:

broken — fix itUnboundLocalError

Run it and read the error. Then let record change the global count.

The rule behind it: assigning to a name inside a function normally makes it local for that whole function, unless declared global or nonlocal. A local can also shadow a global with the same name, and the global stays untouched. global name tells Python to use the outer one instead.

global works, but any function can now change that count from anywhere, which makes bugs hard to trace. There are two cleaner options. Pass the value in and return the new one. Or keep the count inside an enclosing function (the E in the picture) and change it with nonlocal:

python

record still sees count after make_counter has returned. A function that remembers its enclosing names like this is called a closure. Each call of make_counter makes a separate one.

A parameter is a local name for the supplied object

python

On entry, items and original name the same list, so append changes the shared object. The later assignment only rebinds the local name items. It does not retie original. No automatic copy occurs at the call boundary. Decide whether a function mutates an input, returns a new value, or does both, and make that behavior part of its contract.

Closures above also show why “locals disappear” is too broad: an enclosing binding can remain reachable through a returned function. What matters is where a name is visible and which objects remain referenced.

Take a canteen order

A canteen counter takes any number of dishes, plus optional notes. *items collects the extra positional arguments into a tuple. **extras collects the extra named ones into a dict:

python

The mistake is the other direction. You already have the dishes in a list:

What happens when you run this?
def bill(*prices):
    return sum(prices)

plate = [60, 25, 40]
print(bill(plate))

A * at the call spreads a list into arguments (and ** spreads a dict into named ones). A parameter placed after *prices can only be passed by name, so a stray number can never land in it by accident:

python

A bare * does the same with no *args at all: def book(seats, *, window=False) means window must be named.

Traps worth knowing

A default is created once, when Python reads the def, not on every call. With a list, that one list is shared by every call:

What does this print?
def add_item(item, cart=[]):
    cart.append(item)
    return cart

add_item("samosa")
print(add_item("chai"))
  • A function receives the same object you pass, not a copy. .append inside it changes the caller's list. Assigning a new value to the parameter does not.
  • Functions are values. pay = split gives the function another name. split without () does not run it.
  • A function may call itself (recursion). It needs a stopping case that returns without calling itself again.

From function values to smaller subproblems

Two later challenges combine tools you will revisit in the collections and recursion lessons. A lambda x: x * 2 is a function value, like a small def whose body returns one expression. A dict can store it under a name:

python

A recursive tree sum uses the same contract at every node: “return this node's value plus every descendant's value.” For a node 1 with leaf children 2 and 3, the child calls return 2 and 3; the parent combines 1 + 2 + 3. A leaf has no children, so its empty child sum is 0 and no further call occurs. The exercise assumes a finite tree with no cycles. If nested dicts or generator expressions are new, complete the collections lessons before attempting that capstone; they are not prerequisites for the print/return checkpoint.

Quick practice

What does this print?
def add_tip(items):
    items.append(50)

cart = [100, 200]
add_tip(cart)
print(len(cart))
What does this print?
rate = 5

def surge():
    rate = 10

surge()
print(rate)
What happens when you run this?
def fare(km, rate=12):
    return km * rate

print(fare(km=5, 15))
broken — fix it

The greeting comes out backwards. Fix the call, not the function.


🎯 Your turn

Write total_with_tip(subtotal, tip_percent=18). It returns the subtotal plus the tip, rounded to two decimals. tip_percent defaults to 18.

  • total_with_tip(100) → 118.0
  • total_with_tip(100, 20) → 120.0

Hint: give tip_percent a default of 18 in the def line, then return round(subtotal + subtotal * tip_percent / 100, 2).

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from a default greeting to summing a whole tree.

Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — total_with_tip(): Adds a default 18% tip to any subtotal in one call.
Scenario Most guests tip 18%, so the 'quick total' button adds 18% automatically — unless someone picks a different amount.
total_with_tip.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
total_with_tip(subtotal, tip_percent) → floatSubtotal plus tip. tip_percent defaults to 18.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.