CodeMIRAI
0 XP

Defining functions

2 min read 5 runnable examples Quiz included

A function is a named block of code that does one job. You define it once and call it as often as you like. You have already used built-in functions such as print(), len() and input(); now you will write your own.

Defining and calling

Python
def greet():
    print("Hello!")
    print("Welcome to CodeMIRAI.")

greet()
greet()
def area(w, h): · return w * h · x = area(3, 4)callerx = area(3, 4)w=3, h=4arearuns its bodywith w and hreturn 12the caller waits, then x = 12
Arguments go in as parameters, the body runs, and return hands one value back to exactly where the call was.
  • def starts the definition, followed by the function's name and brackets.
  • The indented block underneath is the function's body.
  • Defining a function does not run it. Calling it, greet(), does.

Why bother?

Without functions, you copy and paste code, and every copy is a place for a bug to hide. With a function, you fix it once.

Python
def print_receipt_line(item, price):
    print(f"{item:<12}{price:>8.2f}")

print_receipt_line("Coffee", 3.5)
print_receipt_line("Bagel", 2.25)
print_receipt_line("Orange juice", 4)

Functions also let you give a name to an idea, so code reads like a description of what it does.

Functions can call functions

Python
def line():
    print("-" * 24)

def header(title):
    line()
    print(title.center(24))
    line()

header("Monthly report")

Define before you call

Python reads top to bottom, so a function must be defined before the line that calls it runs:

Python
say_hi()

def say_hi():
    print("hi")

Naming functions

Function names follow the same rules as variables and use snake_case. Good names are usually verbs that say what the function does: calculate_total, send_email, is_valid.

Documenting a function

A docstring describes what a function does; help() shows it:

Python
def area(width, height):
    """Return the area of a rectangle with the given width and height."""
    return width * height

help(area)
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.