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

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:
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:
UnboundLocalErrorRun 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:
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
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:
The mistake is the other direction. You already have the dishes in a list:
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:
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:
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.
.appendinside it changes the caller's list. Assigning a new value to the parameter does not. - Functions are values.
pay = splitgives the function another name.splitwithout()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:
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
def add_tip(items):
items.append(50)
cart = [100, 200]
add_tip(cart)
print(len(cart))rate = 5
def surge():
rate = 10
surge()
print(rate)def fare(km, rate=12):
return km * rate
print(fare(km=5, 15))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.0total_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.