Python · Lesson 5 of 15
Functions
Define reusable blocks with parameters, return values, and default arguments.
- Beginner
- 14 min read
- 3 objectives
Before this lessonLesson 4: Control Flow
What you will learn
- Define functions with def
- Return values
- Use default parameters
A function is a named, reusable block of code. Functions let you avoid copy and paste, give a name to an idea, and test small pieces in isolation. You define one with def, list its parameters in parentheses, and use return to hand a result back to the caller.
Why functions exist
Imagine writing the same five lines of code in ten places. When you find a bug you must fix it ten times, and you will miss one. A function lets you write those five lines once, give them a name, and use that name wherever you need them. Functions are also how big programs stay understandable: each one does one clear job.
A useful mental model is a vending machine. You put something in (the arguments), the machine does its work without you watching, and something comes out (the return value). You do not need to know how it works inside to use it.
Defining and calling
def area_circle(radius):
return 3.14159 * radius ** 2
print(area_circle(2))
result = area_circle(10)12.56636
The values you pass in are called arguments. A function with no return statement returns None. Prefer returning a value over printing inside the function, because a returned value can be reused, tested and combined.
Default and keyword arguments
Give a parameter a default value and callers may omit it. When you call a function you can also name arguments, which makes calls self-documenting and lets you pass them in any order.
def greet(name, excited=False):
msg = f"Hello, {name}"
return msg + "!" if excited else msg
print(greet("world"))
print(greet("world", excited=True))
print(greet(excited=True, name="Ada"))Hello, world Hello, world! Hello, Ada!
Returning several values
Python can return a tuple, and the caller can unpack it into separate names in one line.
def min_max(nums):
return min(nums), max(nums)
low, high = min_max([4, 9, 1, 7])
print(low, high)1 9
Scope
Variables created inside a function are local: they exist only while the function runs. Reading a global variable inside a function is fine, but assigning to it creates a new local one instead. Passing data in through parameters and out through return keeps functions predictable.
The anatomy of a function, step by step
def total_price(price, quantity, tax_rate=0.1):
"""Return the price including tax."""
subtotal = price * quantity
return subtotal * (1 + tax_rate)
print(total_price(20, 3))
print(total_price(20, 3, tax_rate=0))66.0 60
defstarts the definition;total_priceis the name.price, quantity, tax_rate=0.1are the parameters.tax_ratehas a default, so callers may leave it out.- The triple-quoted line is a docstring: a one-sentence description shown by
help(). returnsends the answer back and ends the function immediately.
print versus return
Beginners often confuse these two. print only shows something on the screen; the value is then gone. return hands the value back to the caller so it can be stored, tested or used in more maths.
def add_print(a, b):
print(a + b)
def add_return(a, b):
return a + b
x = add_print(2, 3)
y = add_return(2, 3)
print("x is", x)
print("y is", y * 10)5 x is None y is 50
Functions calling functions
Small functions are easy to test and combine. Build bigger behavior by letting one function call another.
def clean(name):
return name.strip().title()
def greeting(name):
return f"Welcome, {clean(name)}!"
print(greeting(" aDA lovelace "))Welcome, Ada Lovelace!
*args and **kwargs (flexible arguments)
When you do not know how many arguments a caller will pass, *args collects extras into a tuple and **kwargs collects named extras into a dict.
def describe(*args, **kwargs):
print(args)
print(kwargs)
describe(1, 2, 3, color="red", size="M")(1, 2, 3)
{'color': 'red', 'size': 'M'}Key takeaways
- A function names a reusable job: parameters in,
returnvalue out. printdisplays;returngives a value back. Prefer returning.- Defaults make arguments optional; keyword arguments make calls readable.
- Keep functions small and single-purpose, and let them call each other.
# Write your solution here
