Functions Basics
Name a piece of behaviour with def, give it inputs, get a result back with return - and know where its variables live.
What you will be able to do
- Define a function with def, and call it
- Explain why defining a function runs nothing, and why it must be defined before it is called
- Tell parameters from arguments, and match arguments to parameters by position
- Send a value back with return - and know that a function without one returns None
- Explain the difference between printing a value and returning it
- Return several values at once, and use return to leave a function early
- Explain that names created inside a function are local, and what happens to lists you pass in
- Document a function with a docstring, and build bigger functions from small ones
The idea, in plain English
Until now every program ran from top to bottom, and when you needed the same calculation twice you wrote it twice. A function gives a piece of code a NAME, so you can run it whenever you need it - with different inputs each time.
You write it once with def: a name, the inputs it needs (parameters), and the code. Calling it - line_total(250, 2) - runs that code with those values (arguments), and return hands the result back to wherever it was called. Fix a bug in the function and every call is fixed.
Two ideas carry most of this lesson. Returning a value is not the same as printing it - a function that only prints gives back None. And the names a function creates are LOCAL: they exist while it runs and vanish afterwards. Every output below comes from running the code in Python 3.14.
Worked example: Extracting a repeated calculation into a function.
An everyday example: a recipe card
A cook writes a recipe on a card once, and makes the dish from it many times:
- The card has a name at the top: "Masala Tea".
- It lists what it needs: milk, tea leaves, sugar. That is the PARAMETER list - placeholders, not real milk.
- Writing the card cooks nothing. Only when someone USES the card does anything happen.
- Each time, you bring real ingredients - this milk, two spoons of sugar. Those are the ARGUMENTS.
- The card ends with "serve the tea". That is RETURN: the result comes back out to whoever asked.
- The pots and spoons used while cooking stay in the kitchen. Nobody outside sees them. Those are LOCAL variables.
- Improve the card once, and every future cup is better.
Writing the carddef - defines the function. Runs nothing.The name on the cardThe function name - a verb, saying what it does."Needs: milk, sugar"Parameters - names for the inputs.Cooking from the cardCalling the function.This milk, two spoonsArguments - the real values for this call."Serve the tea"return - the result goes back to the caller.Pots stay in the kitchenLocal variables - gone when the function ends.Why functions: the repeated calculation
- Price x quantity, plus 18% GST - the program below does it three times, written out three times.
- If the GST rate changes, you must find and fix every copy. Miss one, and the totals disagree.
- A function writes it ONCE, with a name that says what it does: line_total(price, quantity).
- Each call gives it different values, and it gives back a different result.
- Same answers, a third of the code, and one place to fix.
# Without a function: the same calculation, three times
pen_total = 20 * 3
pen_total = pen_total + pen_total * 0.18
book_total = 250 * 2
book_total = book_total + book_total * 0.18
bag_total = 900 * 1
bag_total = bag_total + bag_total * 0.18
print(pen_total, book_total, bag_total) # 70.8 590.0 1062.0
# With a function: written once, used three times
def line_total(price, quantity):
subtotal = price * quantity
return subtotal + subtotal * 0.18
print(line_total(20, 3), line_total(250, 2), line_total(900, 1)) # 70.8 590.0 1062.0Defining and calling
- def name(): starts a function. The indented lines under it are its body (indentation is syntax - Lesson 1).
- Defining runs NOTHING. Python only remembers the code under that name.
- Calling it - the name followed by brackets, greet() - runs the body. Call it as often as you like.
- Without the brackets, greet is just the function object itself. Printing it shows <function greet at ...>.
- A function must be defined BEFORE the line that calls it runs. Call it too early and you get NameError.
def greet():
print("Hello from inside greet")
print("before")
greet()
greet()
print("after")
# before
# Hello from inside greet
# Hello from inside greet
# after
print(greet) # <function greet at 0x...> - not called, no brackets
print(type(greet).__name__) # functionsay_hi() # NameError: name 'say_hi' is not defined
def say_hi():
print("hi")
say_hi() # hi - defined by nowParameters and arguments
- PARAMETERS are the names in the def line: def add(a, b). They are placeholders.
- ARGUMENTS are the real values in the call: add(2, 3).
- They are matched by POSITION: the first argument goes to the first parameter, and so on.
- So the order matters. describe("Pune", "Ravi") runs fine - and says something wrong.
- Give too few or too many arguments and Python stops with a TypeError that names the problem.
- Python does not check types: add() works on numbers, strings and lists - anything that supports +.
- Lesson 24 adds keyword and default arguments.
def add(a, b): # a and b are PARAMETERS
return a + b
print(add(2, 3)) # 5 - 2 and 3 are ARGUMENTS
x = 10
y = 4
print(add(x, y)) # 14
print(add("Py", "thon")) # Python
print(add([1], [2, 3])) # [1, 2, 3]
def describe(name, city):
return f"{name} lives in {city}"
print(describe("Ravi", "Pune")) # Ravi lives in Pune
print(describe("Pune", "Ravi")) # Pune lives in Ravi - wrong order, no error
add(1)
# TypeError: add() missing 1 required positional argument: 'b'
add(1, 2, 3)
# TypeError: add() takes 2 positional arguments but 3 were givenreturn: sending a value back
- return value ends the function and hands value back to the caller.
- The call then IS that value: square(3) + square(4) is 9 + 16.
- So calls can go anywhere a value can - in a sum, in an f-string, inside another call.
- return ends the function immediately. Lines after it never run.
- That makes "return early" a clean pattern: check the special cases first and return, leaving the normal case at the end.
- A function with no return - or that reaches its end - returns None.
- return a, b returns both, packed in a tuple. Unpack it: low, high = min_max(numbers) (Lesson 17).
def square(n):
return n * n
result = square(4)
print(result) # 16
print(square(3) + square(4)) # 25
print(square(square(2))) # 16
# No return: the function gives back None
def say(text):
print(text)
value = say("hello") # hello
print(value) # None
# return ends the function - check special cases first
def check_age(age):
if age < 0:
return "invalid"
if age < 18:
return "minor"
return "adult"
print("never runs") # after a return - unreachable
print(check_age(-1), check_age(12), check_age(30)) # invalid minor adult
# Several values come back as a tuple
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([7, 2, 9, 4])
print(low, high) # 2 9
print(min_max([7, 2, 9, 4])) # (2, 9)print is not return
The most common beginner bug with functions:
- print() SHOWS a value on the screen. The program cannot use what was shown.
- return GIVES the value back. The program can store it, add to it, pass it on.
- A function that prints its answer, but does not return it, returns None.
- It looks right when you run it - the number appears. It breaks the moment you use the result: None * 2 is a TypeError.
- The rule: functions that WORK something out should return it. Leave printing to the code that calls them.
def total_printing(prices):
print(sum(prices))
def total_returning(prices):
return sum(prices)
a = total_printing([10, 20]) # 30 <- shown, but not given back
b = total_returning([10, 20])
print("a is", a) # a is None
print("b is", b) # b is 30
print(total_returning([10, 20]) * 2) # 60
print(total_printing([10, 20]) * 2)
# 30
# TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'Local names: what stays inside
- Names created inside a function - including its parameters - are LOCAL. They exist only while the function runs.
- After it returns, they are gone. print(prefix) outside the function is a NameError.
- A function CAN read a name defined outside it, like rate below.
- But ASSIGNING to a name inside a function creates a new local one. reset() sets its own count to 0; the outer count stays 10. (Lesson 26 covers this fully.)
- Reassigning a parameter changes only the function’s name for it: double_it(x) leaves x at 5.
- But a list you pass in is the SAME list (names and objects - Lesson 2). If the function changes it - append() - the caller sees the change.
def make_label(name):
prefix = "Student:" # local
return f"{prefix} {name}"
print(make_label("Ravi")) # Student: Ravi
print(prefix) # NameError: name 'prefix' is not defined
# Reading an outer name works
rate = 0.18
def with_tax(amount):
return amount + amount * rate
print(with_tax(100)) # 118.0
# Assigning makes a NEW local name - the outer one is untouched
count = 10
def reset():
count = 0
return count
print(reset(), count) # 0 10
# Reassigning a parameter does not change the caller's variable
def double_it(n):
n = n * 2
return n
x = 5
print(double_it(x), x) # 10 5
# But changing a list you were given changes the caller's list
def add_item(cart, item):
cart.append(item)
my_cart = ["pen"]
add_item(my_cart, "book")
print(my_cart) # ['pen', 'book']Tip: Prefer passing values IN as arguments and getting results OUT with return. A function that only uses its parameters is easy to test and reuse.
Docstrings and naming
- A string on the first line of the body is the function’s DOCSTRING: what it does, in one sentence.
- help(line_total) prints it, along with the parameters - so do editors when you hover over a call.
- Name functions with a verb, in snake_case: calculate_total, send_email, is_valid.
- Functions that answer yes/no read best as questions: is_even(n), has_access(user).
- One function, one job. If its name needs "and", it is probably two functions.
def line_total(price, quantity):
"""Return price x quantity, plus 18% GST."""
subtotal = price * quantity
return subtotal + subtotal * 0.18
print(line_total.__doc__)
# Return price x quantity, plus 18% GST.
help(line_total)
# Help on function line_total in module __main__:
#
# line_total(price, quantity)
# Return price x quantity, plus 18% GST.The worked example: an invoice from small functions
Bigger functions are built from smaller ones. Each does one job, and each can be checked on its own:
- subtotal() - price times quantity.
- gst() - the tax on an amount, using one GST_RATE constant (Lesson 2).
- line_total() - calls subtotal() and gst().
- invoice_total() - adds up line_total() for every line.
- format_rupees() - turns a number into text for display. The only function that deals with how things LOOK.
- If the GST rate changes, one line changes. If the format changes, one function changes.
GST_RATE = 0.18
def subtotal(price, quantity):
"""Price times quantity."""
return price * quantity
def gst(amount):
"""The GST on an amount."""
return round(amount * GST_RATE, 2)
def line_total(price, quantity):
"""Subtotal plus GST for one line of an invoice."""
amount = subtotal(price, quantity)
return amount + gst(amount)
def invoice_total(lines):
"""Add up the line totals of an invoice."""
total = 0
for price, quantity in lines:
total = total + line_total(price, quantity)
return round(total, 2)
def format_rupees(amount):
"""Format a number as rupees with two decimals."""
return f"Rs {amount:,.2f}"
order = [(20, 3), (250, 2), (900, 1)]
for price, quantity in order:
print(f"{price:>5} x {quantity} -> {format_rupees(line_total(price, quantity))}")
print("Total:", format_rupees(invoice_total(order)))
# 20 x 3 -> Rs 70.80
# 250 x 2 -> Rs 590.00
# 900 x 1 -> Rs 1,062.00
# Total: Rs 1,722.80Function basics at a glance
defDefines a function. Runs nothing.
def add(a, b):
ParametersNames for the inputs, in the def line.
(a, b)
CallRuns the body with these arguments.
add(2, 3)
ArgumentsThe real values, matched to parameters by position.
2, 3
returnEnds the function and gives back a value.
return a + b
No returnThe function gives back None.
print(say("hi")) # NoneSeveral valuesReturned as a tuple; unpack them.
low, high = min_max(nums)
DocstringThe first string in the body; shown by help().
"""Return the total."""
Errors you will meet
NameErrorCalling a function before its def has run - or using a local name outside.
name 'say_hi' is not defined
TypeError: missingToo few arguments.
missing 1 required positional argument: 'b'
TypeError: takesToo many arguments.
takes 2 positional arguments but 3 were given
TypeError: 'NoneType'Using the result of a function that printed instead of returning.
unsupported operand type(s) for *: 'NoneType' and 'int'
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Look back at a program from an earlier lesson. Find a calculation written more than once, and turn it into a function.”
“Write total_printing and total_returning from this lesson. Multiply each result by 2 and read the error from the first one.”
“Call describe("Pune", "Ravi"). No error - so how would you notice the mistake?”
“Create a variable inside a function, call the function, then try to print the variable outside it.”
“Pass a list to a function that appends to it, then print the list afterwards. Do the same with a number the function reassigns.”
What usually goes wrong
The value appears on screen, but the function returns None - so using the result fails.
✗ def total(prices):
print(sum(prices))✓ def total(prices):
return sum(prices)Without (), you get the function object, not its result - nothing runs.
✗ result = calculate_total✓ result = calculate_total()Python runs top to bottom. The def must have run before the call does.
✗ greet()
def greet():
print("hi")✓ def greet():
print("hi")
greet()They are matched by position, and Python cannot tell a name from a city. Keep parameter order natural - and Lesson 24’s keyword arguments make calls explicit.
✗ describe("Pune", "Ravi")✓ describe("Ravi", "Pune")return ends the function. Anything below it in the same block never runs.
✗ return total
print("done")✓ print("done")
return totalNames made inside a function vanish when it returns. Return the value and store it.
✗ calculate()
print(result) # NameError✓ result = calculate()
print(result)Best practices
- Give each function one job, and a verb name that says what it is: calculate_total, is_valid.
- Return results; let the caller decide whether to print them.
- Pass values in as arguments instead of reading outer variables.
- Check special cases first and return early, so the main logic is not nested.
- Write a one-line docstring for every function that is not completely obvious.
- Keep functions short - if you cannot see all of it at once, split it.
- Do not change a list you were given unless that is the function’s job - and say so in its name.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Write cube(n) that returns n to the power 3. Check it with 3 and -2.
Show hintHide hint
n ** 3, returned - not printed.
Show solutionHide solution
def cube(n):
return n ** 3
print(cube(3), cube(-2)) # 27 -8Write is_even(n) that returns True for even numbers and False otherwise.
Show hintHide hint
A comparison already is True or False - return it directly, no if needed.
Show solutionHide solution
def is_even(n):
return n % 2 == 0
print(is_even(10), is_even(7)) # True FalseWrite full_name(first, last) that removes extra spaces and returns the name in title case. full_name(" ravi", "KUMAR ") should give "Ravi Kumar".
Show hintHide hint
strip() and title() on each part, then an f-string.
Show solutionHide solution
def full_name(first, last):
return f"{first.strip().title()} {last.strip().title()}"
print(full_name(" ravi", "KUMAR ")) # Ravi KumarWrite average(numbers) that returns the mean - and None for an empty list instead of crashing.
Show hintHide hint
Return early for the empty case. sum([]) / len([]) would divide by zero.
Show solutionHide solution
def average(numbers):
if not numbers:
return None
return sum(numbers) / len(numbers)
print(average([80, 90, 70]), average([])) # 80.0 NoneWrite area(width, height), then use it to add up the areas of a 3 x 4 room and a 5 x 2 room in one line.
Show hintHide hint
Because area() returns, two calls can be added directly.
Show solutionHide solution
def area(width, height):
return width * height
total = area(3, 4) + area(5, 2)
print(total) # 22Write grade(score): "A" for 90 or more, "B" for 75 or more, "C" for 50 or more, otherwise "F". Use early returns, not elif.
Show hintHide hint
Each if returns, so the next one only runs when the earlier ones did not match.
Show solutionHide solution
def grade(score):
if score >= 90:
return "A"
if score >= 75:
return "B"
if score >= 50:
return "C"
return "F"
print([grade(s) for s in [95, 80, 60, 30]]) # ['A', 'B', 'C', 'F']A report card from small functions
Build a class report from four small functions. Each one returns a value; only the loop at the end prints.
- average(marks) returns the mean, rounded to 1 decimal place.
- grade(avg) returns A for 85 or more, B for 60 or more, C for 40 or more, otherwise F.
- passed_all(marks) returns True when every mark is 40 or more.
- report_line(name, marks) returns one formatted line, using the other three functions.
- Give every function a docstring, and print one line per student.
students = {
"Ravi": [78, 85, 92],
"Kiran": [45, 60, 38],
"John": [90, 88, 95],
"Anil": [55, 49, 70],
}
# def average(marks): ...
# def grade(avg): ...
# def passed_all(marks): ...
# def report_line(name, marks): ...
for name, marks in students.items():
...
Show one solutionHide solution
def average(marks):
"""The mean of a list of marks, rounded to 1 decimal place."""
return round(sum(marks) / len(marks), 1)
def grade(avg):
"""A letter grade for an average."""
if avg >= 85:
return "A"
if avg >= 60:
return "B"
if avg >= 40:
return "C"
return "F"
def passed_all(marks):
"""True when every mark is 40 or more."""
return all(m >= 40 for m in marks)
def report_line(name, marks):
"""One line of the report, built from the other functions."""
avg = average(marks)
status = "passed" if passed_all(marks) else "needs re-test"
return f"{name:<6} avg {avg:>5} grade {grade(avg)} {status}"
students = {
"Ravi": [78, 85, 92],
"Kiran": [45, 60, 38],
"John": [90, 88, 95],
"Anil": [55, 49, 70],
}
for name, marks in students.items():
print(report_line(name, marks))
# Ravi avg 85.0 grade A passed
# Kiran avg 47.7 grade C needs re-test
# John avg 91.0 grade A passed
# Anil avg 58.0 grade C passedKey points
- A function gives a piece of code a name, so you can run it again with different inputs.
- def defines it and runs nothing; calling it - name(arguments) - runs the body.
- The def must run before the call; otherwise NameError.
- Parameters are the names in the def; arguments are the values in the call, matched by position.
- return ends the function and gives a value back; without it the function returns None.
- Printing shows a value; returning gives it back. Functions that work something out should return it.
- return a, b returns a tuple - unpack it with low, high = f(...).
- Names created inside a function are local and vanish when it returns.
- Assigning inside a function makes a new local name; changing a list you were passed changes the caller’s list.
- Docstrings describe a function; help() shows them.
Quick check before you move on
Interview questions
What is the difference between a parameter and an argument?
A parameter is the name in the function definition; an argument is the actual value passed in a call. In def add(a, b) and add(2, 3), a and b are parameters, 2 and 3 are arguments.
What does a Python function return if there is no return statement?
None. Reaching the end of the body, or a bare return, both return None - which is why the result of a print-only function is None.
Is Python pass-by-value or pass-by-reference?
Neither, exactly - it is pass-by-object-reference (call by sharing). The parameter is bound to the same object the caller passed. Mutating that object is visible to the caller; rebinding the parameter to a new object is not.
How can a function return more than one value?
return a, b builds a tuple, and the caller unpacks it: x, y = f(). For many values, a dictionary or a dataclass is clearer than a long tuple.
What makes a function easy to test?
It does one job, takes its inputs as arguments, returns its result instead of printing, and does not change outer state. Given the same arguments it gives the same result, so a test is just a call and a comparison.
Quiz
- 1.
Why use a function instead of copying the same code?
- 2.
What is the difference between print and return in a function?
- 3.
What happens to the lines after a return statement?
- 4.
A function appends to a list it was given. Does the caller see the change?
- 5.
Why does calling a function above its def raise NameError?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...