← Python Crash Course

PCC·08 · Chapter record

Functions

Chapter 8 — packaging code so you only write it once

Done

Five sessions on functions: defining and calling them, keyword arguments and defaults, returning values, passing lists in and letting functions modify them, and accepting an arbitrary number of arguments. Each one explains the concept, lists the key terms, then gives you exercises — try them yourself before revealing the code.

8.1

Defining a Function

  • def starts a function definition; the indented block below is the function body, and you run it by calling the name with parentheses.
  • A docstring — a triple-quoted string right after def — documents what the function does.
  • A parameter is the name listed in the function definition; an argument is the actual value you pass when calling it.
  • Positional arguments are matched to parameters by order — mix up the order and you get mismatched, often nonsensical, results.
def
the keyword that starts a function definition
parameter
a name listed in the function definition
argument
the actual value passed when the function is called
docstring
a triple-quoted string documenting what a function does
Activity 1

Write a function called display_message() that prints one sentence about what you're learning in this chapter, then call it.

Activity 2

Write a function favorite_book(title) that prints a sentence like "One of my favorite books is <title>." Call it with a book title.

▶ Pet Describer