Functions
Package code you can reuse
In this lesson
A function is a named, reusable block of code. You define it once, then ‘call’ it whenever you need that work done. Functions are how you keep programs organised, avoid repetition, and build up larger ideas from small pieces.
Explain it like I’m 5
A function is a recipe with a name. Once you’ve written the recipe, you just say its name to make the dish again — you don’t rewrite the steps each time.
Defining and calling
You define a function with def, a name, parentheses, and a colon, then an indented body: def greet():. Defining it doesn’t run it — you call it by writing its name with parentheses: greet(). This separation lets you describe the work once and trigger it many times.
def greet():
print("Hello there!")
greet()
greet()
Hello there! Hello there!
Parameters and arguments
Functions become useful when they take input. Parameters are the names in the definition; arguments are the actual values you pass when calling. def greet(name): has a parameter name; greet("Ada") passes the argument ‘Ada’. Inside the function, name holds whatever was passed.
def greet(name):
print("Hi,", name)
greet("Ada")
greet("Sam")
Hi, Ada Hi, Sam
Returning a result
return sends a value back to the caller, who can store or use it: total = add(2, 3). A function without return gives back None. Crucial distinction: print() shows a value on screen but the program can’t reuse it; return hands the value back so the rest of your code can work with it. Most functions should return, not print.
def area(width, height):
return width * height
living_room = area(5, 4)
print("Area:", living_room)
print("Double:", area(5, 4) * 2)
Area: 20 Double: 40
Finish celsius_to_fahrenheit so it returns the converted temperature. The formula is c * 9 / 5 + 32.
def celsius_to_fahrenheit(c):
return ___
print(celsius_to_fahrenheit(0))
print(celsius_to_fahrenheit(100))
Replace ___ with the formula c * 9 / 5 + 32 and keep the return.
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
print(celsius_to_fahrenheit(0))
print(celsius_to_fahrenheit(100))
32.0
212.0
Default and keyword arguments
You can give parameters defaults: def greet(name, greeting="Hello"): lets callers omit greeting. You can also pass arguments by name for clarity: greet("Ada", greeting="Hi"). Defaults make functions flexible without forcing every caller to supply every value.
def greet(name, greeting="Hello"):
return greeting + ", " + name + "!"
print(greet("Ada"))
print(greet("Sam", greeting="Welcome"))
Hello, Ada! Welcome, Sam!
Flexible arguments: *args and **kwargs
Sometimes a function should accept any number of arguments. A parameter written *args collects all the extra positional arguments into a tuple; **kwargs collects extra named arguments into a dictionary. You’ll see these everywhere in library code.
(The names args and kwargs are just convention — it’s the * and ** that matter. And remember: variables created inside a function are private to it, as covered in variable scope.)
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3))
print(total(10, 20))
def describe(**facts):
for key, value in facts.items():
print(key, "=", value)
describe(name="Ada", role="pioneer")
6 30 name = Ada role = pioneer
Common mistake: Printing inside a function when you needed to return
Beginners often print() the result, then try to use the function’s value elsewhere — but it returned None.
Use return to send the value back; let the caller decide whether to print it. Reserve printing for the outermost ‘show the user’ step.
def double(n):
return n * 2 # return, don't print
result = double(5)
print(result)
Common mistake: Forgetting the parentheses when calling
Writing greet without () refers to the function object instead of running it.
Call a function with parentheses: greet(). Pass any arguments inside them.
What does return do?
return hands a value back to the caller; print() is what displays text.
In def greet(name):, what is name?
name is a parameter; the value you pass when calling is the argument.
Mini exercise (easy)
Write a function is_even(n) that returns True if n is even and False otherwise, then print the result for 4 and 7.
Do it here. Finish the code below and press Run to try your answer right in the browser — no setup needed.
def is_even(n):
# return True if n is even, else False
return False
print(is_even(4), is_even(7))
A number is even when n % 2 == 0. Return that comparison directly.
def is_even(n):
return n % 2 == 0
print(is_even(4), is_even(7))
True False
assert is_even(4) is True and is_even(7) is False, "is_even(4) should be True and is_even(7) should be False"
print("✓ Correct!")