Python Essentials · 14 min · 110 XP

Functions, parameters and return

Define a function, pass values into it, and return a result before later lessons ask you to build with functions.

A function gives a small job a name. Define it with def, put its inputs (the parameters) in parentheses, and indent the body. Defining a function does not run it. Call it by writing its name with values in parentheses.

Define once, call with different values
def area(width, height):
    return width * height

small = area(3, 4)
large = area(10, 8)
print(small, large)  # 12 80

return hands a value back to the calling code. print only displays something. If a function has no return, its result is None. Keep calculations inside the function and decide where to print outside it; that makes the function reusable and testable.

Returning and printing are different jobs
def greeting(name):
    return f"Hello, {name}!"

message = greeting("Ada")
print(message.upper())  # HELLO, ADA!

Names created inside a function are local to that call. Give a function everything it needs as parameters instead of relying on mystery values elsewhere in the file. Later you will learn defaults and keyword arguments; for now, make every required input explicit.

Loading your workspace…