PCC·08 · Chapter record
Functions
Chapter 8 — packaging code so you only write it once
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.
Defining a Function
Concept
defstarts 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.
Key Terms
- 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
Exercise
Write a function called display_message() that prints one sentence about what you're learning in this chapter, then call it.
Write a function favorite_book(title) that prints a sentence like "One of my favorite books is <title>." Call it with a book title.
Keyword Arguments & Default Values
Concept
- A keyword argument names the parameter directly in the call — order stops mattering, and there's no risk of mismatched values.
- A default value in the function definition makes that argument optional — omit it in the call, and Python falls back to the default.
- Any parameter with a default value must come after all parameters that don't have one.
Key Terms
- keyword argument
- a name=value pair passed in a function call
- default value
- a fallback value used when no argument is provided
Exercise
Write a function that describes a T-shirt: size and text, with text defaulting to "I love Python". Call it once with just a size, and once overriding the text.
Call the same function three times using keyword arguments in a different order each time, and confirm the output never changes.
Return Values
Concept
returnsends a value back to the line that called the function — the function itself doesn't have to print anything.- Give a parameter a default value like
middle_name=''to make it optional, then branch on it with an if to build the result differently. - A function can return any kind of value, including a whole dictionary it builds up internally.
Key Terms
- return
- sends a value back to the calling line
- return value
- the value a function hands back
Exercise
Write city_country(city, country) that returns a string like "Santiago, Chile". Call it with three different city-country pairs and print each result.
Write make_album(artist, title, songs=None) that returns a dictionary — and adds a song count to the dictionary only when one is given.
Passing a List
Concept
- Pass a list to a function and the function gets direct access to its actual contents — looping over it, printing from it, whatever it needs.
- Changes a function makes to a list it received are permanent — it's the same list, not a copy, so the caller sees the change too.
- Splitting work into small, single-job functions — one that mutates, one that reports — keeps the main program short and easy to follow.
- Pass
list_name[:]instead oflist_nameto hand the function a copy — changes inside the function then leave your original untouched.
Key Terms
- list_name[:]
- a copy of the list, so the function can't modify the original
Exercise
Make a list of short text messages. Pass it to a function show_messages() that prints each one.
Write send_messages() that prints each message and moves it into a new sent_messages list. Call it once with the real list, and once with a copy (list[:]) — compare what happens to the original.
Arbitrary Arguments
Concept
*toppingsin a function definition packs any number of positional arguments into a tuple — call it with 1 topping or 10, it just works.- Mix a fixed parameter with
*args, and the fixed one must come first:def make_pizza(size, *toppings):. - **user_info packs any number of keyword arguments into a dictionary — perfect when you don't know ahead of time what information you'll receive.
Key Terms
- *args
- collects extra positional arguments into a tuple
- **kwargs
- collects extra keyword arguments into a dictionary
Exercise
Write make_sandwich(*items) that prints each ingredient. Call it with 1, 3, and 5 ingredients to prove it handles any amount.