Defining functions
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
def greet():
print("Hello!")
print("Welcome to CodeMIRAI.")
greet()
greet()defstarts 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.
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
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:
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:
def area(width, height):
"""Return the area of a rectangle with the given width and height."""
return width * height
help(area)