These are the notes for Python episode 13. Last episode we built Raju's billing counter. It works for one customer, but with three customers the same billing lines get copy-pasted three times, and when the GST rule changes, one copy is missed and a customer is billed wrong with no error at all. So we invent the function: steps written once, given a name, and used as often as you like. You will learn def and calling, why calling before def is a NameError, parameters and arguments, the missing-argument TypeError, print versus return (and where None comes from), early return and dead code, returning two values as a tuple, default values, keyword and positional arguments, the order rule for defaults, too many arguments, and docstrings. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13.
The problem: three customers, one rule
Raju's bill is simple: add up the items, then add 5% GST (Goods and Services Tax, the tax added to the bill). Three customers come in: Asha, Ravi and Meena. The quick way is to copy the billing lines once per customer:
# Asha's order
total = 10 + 15 + 20
total = total + total * 5 / 100
print("Asha pays", total)
# Ravi's order
total = 10 + 10
total = total + total * 5 / 100
print("Ravi pays", total)
# Meena's order
total = 25 + 15
total = total + total * 5 / 100
print("Meena pays", total)
Output:
Asha pays 47.25
Ravi pays 21.0
Meena pays 42.0
Three correct bills, but the same two lines appear three times. Now GST becomes 12%. We change it in Asha's block and in Ravi's block, but Meena's block is far down the file and we miss it:
# Asha's order
total = 10 + 15 + 20
total = total + total * 12 / 100
print("Asha pays", total)
# Ravi's order
total = 10 + 10
total = total + total * 12 / 100
print("Ravi pays", total)
# Meena's order
total = 25 + 15
total = total + total * 5 / 100
print("Meena pays", total)
Output:
Asha pays 50.4
Ravi pays 22.4
Meena pays 42.0
Meena pays ₹42. With 12% GST it should be ₹44.8. No error, no warning, just a wrong bill. Why: one rule (the GST calculation) lives in three places, and every copy is a place to forget. With a hundred customers, it's a hundred places.
def: write the steps once
| In the kitchen | In Python |
|---|---|
| A recipe card: the steps written once, with a name | def greet(): defines the function |
| "Make chai!": use the steps by name, as often as you like | greet() calls the function |
| Put tomatoes into the mixer-grinder: what goes in | bill(100): the argument |
| Get chutney back: what comes out | return: the result |
A function is a named block of steps. You write it with def (short for define), a name, round brackets and a colon. The steps go inside, indented, just like an if block.
def greet():
print("Welcome to Raju's stall!")
print("Chai is ready.")
greet()
greet()
Output:
Welcome to Raju's stall!
Chai is ready.
Welcome to Raju's stall!
Chai is ready.
- The
defblock alone prints nothing. Defining a function only writes the recipe card. - To use it, you call it: its name with round brackets,
greet(). Calling means "go run those steps, then come back here". - One definition, two calls, two greetings.
Calling before def: NameError
Order matters. Python reads top to bottom:
greet()
def greet():
print("Welcome!")
Output:
Traceback (most recent call last):
File "main.py", line 1, in <module>
greet()
^^^^^
NameError: name 'greet' is not defined
On line 1, Python has never heard of greet; the def comes later. Define first, then call.
Parameters and arguments
Our greeting says the same thing to everyone. Raju wants to greet each customer by name, so we give the function an input: a name inside the round brackets of def.
def greet(name):
print("Welcome,", name)
greet("Asha")
greet("Ravi")
Output:
Welcome, Asha
Welcome, Ravi
One function, different results, because the input was different.
| Word | Where it lives | Think of it as |
|---|---|---|
| Parameter | in the def line: def greet(name): |
the empty slot |
| Argument | in the call: greet("Asha") |
the value that fills the slot |
When the function runs, the parameter name works like a variable holding the argument "Asha".
Forgetting the argument: TypeError
def greet(name):
print("Welcome,", name)
greet("Asha")
greet("Ravi")
greet()
Output:
Welcome, Asha
Welcome, Ravi
Traceback (most recent call last):
File "main.py", line 6, in <module>
greet()
~~~~~^^
TypeError: greet() missing 1 required positional argument: 'name'
The first two calls work. The third leaves the slot empty, so Python refuses to run the function. name is a required parameter: every call must fill it.
Anatomy of a function
def greet(name): # definition: def, name, parameters, colon
print("Welcome,", name) # body (indented)
greet("Asha") # call: name, arguments
nameis the parameter (slot);"Asha"is the argument (value).- Call before
def→NameError. - Missing argument →
TypeError.
print vs return
| Asking a friend to work out a bill | In Python |
|---|---|
| They shout "105!" and walk away. You heard it, but have nothing written down | print: the answer is shown, then gone |
| They hand you a slip with 105 on it. You can keep it and add to it | return: the answer is handed back to you |
First, the shouting friend. bill prints the amount with GST. We store the result in total, print total, and add ₹10 for a cold drink:
def bill(amount):
print("Bill:", amount + amount * 5 / 100)
total = bill(100)
print("total is", total)
print(total + 10)
Output:
Bill: 105.0
total is None
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(total + 10)
~~~~~~^~~~
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
The bill is shown, but total is None, and None + 10 crashes. Why: print only shows a value on the screen. The function handed nothing back, and a function that hands nothing back gives None, Python's word for "no value" (its type is NoneType).
The fix is return, which hands the answer back to the line that called the function:
def bill(amount):
return amount + amount * 5 / 100
total = bill(100)
print("total is", total)
print(total + 10)
print(bill(200) + bill(40))
Output:
total is 105.0
115.0
252.0
total = bill(100): the call is replaced by the returned value,105.0.- The returned value is a real value: you can store it, add to it, even add two bills together (
210.0 + 42.0 = 252.0). printshows.returngives back. A function with noreturnreturnsNone.
Early return and dead code
return does one more thing: it ends the function, right there.
def check_age(age):
if age < 18:
return "Too young to vote"
return "You can vote"
print("This line never runs")
print(check_age(15))
print(check_age(30))
Output:
Too young to vote
You can vote
- For 15, the first
returnruns and the function ends; the rest is skipped. That's why noelseis needed. This line never runsnever printed: once a function returns, it's finished. Code after areturnthat can never be reached is dead code. Delete it.
Returning two values
Raju wants both the total and the tax. Return them separated by a comma:
def bill(amount):
tax = amount * 5 / 100
return amount + tax, tax
total, tax = bill(200)
print("Total:", total, "Tax:", tax)
Output:
Total: 210.0 Tax: 10.0
Python packs the two values into a tuple, and we unpack it into total and tax, just like in episode 11. If you don't unpack, you can see the tuple itself:
def bill(amount):
tax = amount * 5 / 100
return amount + tax, tax
result = bill(200)
print(result)
print(type(result))
Output:
(210.0, 10.0)
<class 'tuple'>
Default values
| At the chai stall | In Python |
|---|---|
| "One chai": sugar is normal unless you say otherwise | gst=5: a default value |
| "One chai, less sugar": change one thing only when you need it | bill(100, 12): override the default |
| "Sugar: none, milk: extra": name what you're changing | bill(100, tip=20): a keyword argument |
GST is almost always 5. So in the def line, write gst=5. That's a default value: used when the caller doesn't give one. And a tip, defaulting to 0:
def bill(amount, gst=5, tip=0):
return amount + amount * gst / 100 + tip
print(bill(100))
print(bill(100, 12))
print(bill(100, tip=20))
print(bill(amount=100, gst=0))
Output:
105.0
112.0
125.0
100.0
| Call | amount |
gst |
tip |
Result |
|---|---|---|---|---|
bill(100) |
100 | 5 (default) | 0 (default) | 105.0 |
bill(100, 12) |
100 | 12 | 0 (default) | 112.0 |
bill(100, tip=20) |
100 | 5 (default) | 20 | 125.0 |
bill(amount=100, gst=0) |
100 | 0 | 0 (default) | 100.0 |
Keyword vs positional arguments
- A positional argument has no name; it's matched by its position: in
bill(100, 12), the first value goes toamount, the second togst. - A keyword argument names the parameter:
tip=20. That lets you skipgstand still settip, and with names the order doesn't matter:bill(gst=0, amount=100)works too. - Positional arguments must come before keyword arguments in a call (see Common mistakes).
Default before required: SyntaxError
What if the default comes first?
def bill(gst=5, amount):
return amount + amount * gst / 100
Output:
File "main.py", line 1
def bill(gst=5, amount):
^^^^^^
SyntaxError: parameter without a default follows parameter with a default
If gst could be skipped, Python couldn't tell whether bill(100) means the amount or the GST. Required parameters come first, defaults last. Because it's a SyntaxError, nothing in the file runs at all.
Too many arguments: TypeError
bill takes up to three arguments. Give it four:
def bill(amount, gst=5, tip=0):
return amount + amount * gst / 100 + tip
print(bill(100, 5, 10, 2))
Output:
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(bill(100, 5, 10, 2))
~~~~^^^^^^^^^^^^^^^
TypeError: bill() takes from 1 to 3 positional arguments but 4 were given
One required parameter and two optional ones means 1 to 3 arguments; 4 is too many.
Docstrings
A string in triple quotes right under the def line is a docstring: a note saying what the function does. Python keeps it in bill.__doc__ (double underscore, doc, double underscore).
def bill(amount, gst=5):
"""Return the amount with GST added."""
return amount + amount * gst / 100
print(bill.__doc__)
print(bill(100))
Output:
Return the amount with GST added.
105.0
Editors show the docstring when you hover over the function, so write one for every function you share. A docstring is the function's label; a # comment is a note for whoever reads that line of code.
The copy-paste problem, fixed
Back to the three customers: one bill function, three calls.
def bill(amount, gst=5):
return amount + amount * gst / 100
print("Asha pays", bill(10 + 15 + 20))
print("Ravi pays", bill(10 + 10))
print("Meena pays", bill(25 + 15))
Output:
Asha pays 47.25
Ravi pays 21.0
Meena pays 42.0
Three correct bills, and the GST rule lives in exactly one place. GST goes to 12%? Change gst=5 to gst=12 in line 1, and every customer is billed right, Meena included. Nothing to forget. Change once, fixed everywhere. That's the function.
Common mistakes
| Mistake | What you see | Why | Fix |
|---|---|---|---|
| copy-pasting the same lines for each case | no error, a wrong bill | one rule in many places; one copy was missed | one function, many calls |
greet() before def greet(): |
NameError: name 'greet' is not defined |
Python hasn't read the def yet |
define first, then call |
greet() when it's def greet(name): |
TypeError: greet() missing 1 required positional argument: 'name' |
the slot is empty | greet("Asha") |
print inside, no return |
total is None, then TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' |
the function gave back None |
return the value |
code after return |
no error, the line never runs | return ends the function |
delete it, or move it before return |
def bill(gst=5, amount): |
SyntaxError: parameter without a default follows parameter with a default |
defaults must come last | def bill(amount, gst=5): |
bill(100, 5, 10, 2) |
TypeError: bill() takes from 1 to 3 positional arguments but 4 were given |
more arguments than parameters | pass at most 3 |
bill(gst=12, 100) |
SyntaxError: positional argument follows keyword argument |
positional arguments must come first | bill(100, gst=12) |
greet without brackets |
no error, nothing happens | the function was named, not called | greet() |
Mini project: train ticket fare
A function that takes the distance in km, the coach (default "sleeper") and whether the passenger is a senior citizen (default False). Each coach has a rate per km, kept in a dictionary: sleeper ₹0.5, AC 3 ₹1.25, AC 2 ₹1.8. Senior citizens pay 60%. The function returns the fare, rounded.
# Mini project: train ticket fare
def fare(km, coach="sleeper", senior=False):
rate = {"sleeper": 0.5, "ac3": 1.25, "ac2": 1.8}
price = km * rate[coach]
if senior:
price = price * 60 / 100
return round(price)
print("Delhi-Jaipur sleeper:", fare(300))
print("Delhi-Jaipur AC 3:", fare(300, "ac3"))
print("Senior, AC 2:", fare(300, "ac2", senior=True))
Output:
Delhi-Jaipur sleeper: 150
Delhi-Jaipur AC 3: 375
Senior, AC 2: 324
fare(300)uses both defaults: 300 × 0.5 = 150.fare(300, "ac3")overridescoachby position: 300 × 1.25 = 375.fare(300, "ac2", senior=True): 300 × 1.8 = 540, and 60% of 540 = 324.senior=Trueis a keyword argument, so the call reads like a sentence.
Extend it: add a Tatkal option, a keyword argument tatkal=False that adds a flat ₹100.
Solution
def fare(km, coach="sleeper", senior=False, tatkal=False):
rate = {"sleeper": 0.5, "ac3": 1.25, "ac2": 1.8}
price = km * rate[coach]
if senior:
price = price * 60 / 100
if tatkal:
price = price + 100
return round(price)
print(fare(300))
print(fare(300, "ac3", tatkal=True))
print(fare(300, "ac2", senior=True, tatkal=True))
Output:
150
475
424
The old calls still work unchanged, because the new parameter has a default.
Practice
1. Write area(length, width=None) that returns the area of a rectangle, or of a square if width is missing.
Solution
def area(length, width=None):
if width is None:
width = length
return length * width
print(area(4))
print(area(4, 6))
Output:
16
24
None as a default means "not given"; width is None checks for it.
2. Write is_even(n) that returns True or False, and use it in a loop.
Solution
def is_even(n):
return n % 2 == 0
print(is_even(10))
print(is_even(7))
for x in range(1, 6):
if is_even(x):
print(x, "is even")
Output:
True
False
2 is even
4 is even
n % 2 == 0 is already True or False, so return it directly; no if needed.
3. Write max_of_three(a, b, c) without using max().
Solution
def max_of_three(a, b, c):
biggest = a
if b > biggest:
biggest = b
if c > biggest:
biggest = c
return biggest
print(max_of_three(4, 9, 2))
print(max_of_three(7, 7, 3))
print(max_of_three(-5, -1, -8))
Output:
9
7
-1
4. Write count_vowels(text) that returns how many vowels a string has (any case).
Solution
def count_vowels(text):
count = 0
for ch in text.lower():
if ch in "aeiou":
count += 1
return count
print(count_vowels("SyntaxPilot"))
print(count_vowels("Raju's chai stall"))
Output:
3
5
5. Write stats(marks) that returns the average and the highest mark of a list, with a docstring.
Solution
def stats(marks):
"""Return the average and the highest mark."""
avg = sum(marks) / len(marks)
return avg, max(marks)
average, best = stats([85, 92, 78])
print("Average:", average, "Best:", best)
print(stats([70, 64]))
Output:
Average: 85.0 Best: 92
(67.0, 70)
6. Combine episode 12 and 13: write order_total(order, gst=5) where order is a dictionary of item → quantity, priced from a menu dictionary.
Solution
menu = {"chai": 10, "samosa": 15, "vada pav": 20, "lassi": 25}
def order_total(order, gst=5):
total = 0
for item, qty in order.items():
total += menu[item] * qty
return total + total * gst / 100
print(order_total({"chai": 2, "samosa": 1}))
print(order_total({"lassi": 2}, gst=12))
Output:
36.75
56.0
(2 × 10 + 15 = 35, plus 5% = 36.75; 2 × 25 = 50, plus 12% = 56.0.)
Quick quiz
1. (From the video.) What does this print? 12, 15, 18, or TypeError?
def f(x, y=2):
return x * y
print(f(3) + f(3, 3))
Answer
15. f(3) uses the default y=2 and returns 6; f(3, 3) returns 9. 6 + 9 = 15.
2. What does this print?
def show(x):
print(x * 2)
result = show(4)
print(result)
Answer
8
None
show prints 8 but has no return, so result is None.
3. What does this print?
def f(a, b=10):
return a - b
print(f(b=3, a=20))
Answer
17. With keyword arguments the order doesn't matter: a is 20, b is 3.
4. What does this print?
def first_even(nums):
for n in nums:
if n % 2 == 0:
return n
return "none"
print(first_even([3, 7, 8, 10]))
print(first_even([1, 5]))
Answer
8
none
return inside the loop ends the whole function at the first even number, so 10 is never reached. If no number is even, the loop finishes and the last line returns "none".
Interview questions
- What is a function, and why use one? A named, reusable block of code. It removes copy-paste: one rule lives in one place, so a change is made once and can't be missed.
- Parameter vs argument? A parameter is the name in the
defline (the slot); an argument is the value passed in the call (what fills it). printvsreturn?printshows a value on the screen;returnhands a value back to the caller so it can be stored and used. A function withoutreturnreturnsNone.- Can a function return more than one value? Yes:
return a, breturns a tuple, which the caller can unpack withx, y = f(). - What happens to code after
return? It never runs;returnends the function immediately. Such code is dead code. - Positional vs keyword arguments? Positional arguments are matched by position; keyword arguments name the parameter (
tip=20), so they can skip defaults and come in any order. Positional ones must come first. - Why must default parameters come after required ones? Otherwise Python can't tell which positional value fills which slot, so
def f(a=1, b):is aSyntaxError.
Bonus (beyond the video): the mutable default trap
A default value is created once, when the def line runs, not on every call. If that default is a list and the function changes it, the change carries over to the next call:
def add_item(item, order=[]):
order.append(item)
return order
print(add_item("chai"))
print(add_item("samosa"))
Output:
['chai']
['chai', 'samosa']
The second customer's order already contains the first customer's chai. The standard fix is a None default, with a fresh list made inside:
def add_item(item, order=None):
if order is None:
order = []
order.append(item)
return order
print(add_item("chai"))
print(add_item("samosa"))
Output:
['chai']
['samosa']
Rule of thumb: use only immutable defaults (numbers, strings, True/False, None, tuples). This is a well-known interview question.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Function | A named, reusable block of steps | bill |
def |
The keyword that defines a function | def bill(amount): |
| Define | Write the function (the recipe card); runs nothing yet | the def block |
| Call | Run a function by its name with round brackets | bill(100) |
| Body | The indented steps inside a function | return amount + ... |
| Parameter | A name in the def line; a slot for a value |
amount, gst |
| Argument | The value passed in a call; fills a parameter | 100, "Asha" |
| Required parameter | A parameter with no default; every call must fill it | amount |
| Positional argument | An argument matched by its position | bill(100, 12) |
| Keyword argument | An argument that names its parameter | bill(100, tip=20) |
| Default value | The value a parameter uses when no argument is given | gst=5 |
return |
Hands a value back to the caller and ends the function | return total |
| Return value | The value a call gives back | 105.0 |
None |
Python's "no value"; what a function returns without return |
total is None |
NoneType |
The type of None |
'NoneType' and 'int' |
| Early return | A return that ends the function before its last line |
return "Too young to vote" |
| Dead code | Code that can never run, e.g. after return |
print("This line never runs") |
| Tuple return | Returning several values, packed into a tuple | return total, tax |
| Unpacking | Splitting a tuple into variables | total, tax = bill(200) |
| Docstring | A triple-quoted note right under def saying what the function does |
"""Return the amount with GST added.""" |
__doc__ |
Where Python stores a function's docstring | bill.__doc__ |
NameError |
Using a name Python doesn't know yet | calling before def |
TypeError |
A value or call of the wrong kind | missing or too many arguments, None + 10 |
SyntaxError |
Code Python can't even read; nothing runs | def bill(gst=5, amount): |
| Copy-paste code | The same lines repeated for each case | three billing blocks |
| GST | Goods and Services Tax, added to a bill in India | 5% of ₹100 is ₹5 |
| Mutable default (bonus) | A list (or other changeable) default shared between calls | def f(x, items=[]): |
Summary
- Copy-pasted code spreads one rule over many places, and a missed copy is a silent bug.
def name(params):defines a function;name(args)calls it. Define before you call, or it's aNameError.- A parameter is the slot, an argument is the value. A missing required argument is a
TypeError. printshows,returngives back. Noreturnmeans the function returnsNone.returnends the function immediately; code after it is dead.return a, breturns a tuple.- Defaults:
def bill(amount, gst=5):, required parameters first, defaults last. - Keyword arguments (
tip=20) name what they set; positional arguments are matched by position and must come first. - A docstring under
defsays what the function does.
Next episode: scope, *args and **kwargs. Raju tries to keep a running total of the day's sales inside a function, and Python says the variable doesn't exist. Plus functions that take any number of arguments.