Functions, more
Last updated
Lesson 1.8 made functions with a fixed list of parameters. In this lesson you'll call them by name, write functions that take any number of values, see where a function's names live, pass functions around like any other value, sort with a key, and meet the one default value that catches out nearly every Python programmer.
By the end of this lesson you can
- Call functions with keyword arguments, and write functions that take
*argsand**kwargs - Explain which names a function can see, and why its own names vanish when it returns
- Pass a function, or a
lambda, as a value, for example tosorted(key=...) - Avoid a list as a default value, and use
Noneinstead
Keyword arguments
In lesson 1.8 you saw that arguments can be matched by name. That matters more as functions grow. lend has four parameters, two with defaults. Line 9 passes days=7 by name and leaves renew at its default; line 10 skips days and sets renew.
lend("Emma", "Sam", 7, True) would work too, but a reader has to look up lend to know what 7 and True mean. Naming them, days=7, renew=True, makes the call explain itself. Positional arguments always come first: lend(member="Lin", "Beloved") is a SyntaxError.
Any number of values
Sometimes you don't know how many values a function will get. A parameter with one star, *fines, collects all the extra positional arguments into a tuple. Called with nothing, it's an empty tuple.
Two stars, **details, collect the extra keyword arguments into a dictionary, with the names as keys.
The names args and kwargs are only a habit; the stars do the work. You've used a function like this since lesson 1.1: print takes any number of values, which is why print("a", "b", "c") works.
Where names live: scope
Watch it run. While fine_for runs, the Values table shows only days and amount, the function's local names. They're made when the function is called and thrown away when it returns.
Line 5 can still read fine_per_day, a global name made at the top level of the file. A function can read the names around it.
Now try to read the function's local name from outside. Press Run:
NameError: name 'amount' is not defined. By line 10, fine_for has returned and amount is gone. The way to get a value out of a function is the one you already know: return it, and keep what the call gives back, as total does.
Assigning works differently from reading. If a function writes fine_per_day = 30, that makes a new local name, and the global one stays at 25. Python has a global statement to change that, but programs that change globals from inside functions are hard to follow. Pass values in and return results instead.
Functions are values
A function's name is a name like any other, and the function is a value. Line 9 gives the same function a second name, say. Line 10 puts two functions in a list and calls each in turn. Note the difference: shout is the function, shout(...) calls it.
apply_to_all takes a function as a parameter and calls it on every item.
Line 20 passes a lambda: a small function with no name, written in one line. lambda t: t[:3] means "take t and give back its first three characters". A lambda can hold only one expression, whose value it returns. Use it for small jobs passed straight to another function; if it needs a name, write a def.
Sorting with a key
sorted() gives back a new, sorted list. Sorting tuples compares their first items, so books would come out in title order. To sort by something else, pass a key: a function that sorted calls on each item, then sorts by what it gives back.
Line 8 sorts by year, using year_of. Line 10 sorts by page count, with a lambda.
Line 14 fixes a surprise from line 13: capital letters sort before small ones, so "Dune" came first. key=str.lower compares the small-letter version of each title, without changing the titles themselves. Add reverse=True for largest first. The list method .sort() takes the same key and reverse, but sorts the list in place.
A list as a default
add_loan starts a new list of loans when none is passed in. Ada and Sam each borrow one book. Press Run and read what Sam has.
Watch it run to see it: ada and sam end up as the same list. This only bites with values that can change, like lists and dictionaries; a default of 14 or "Dune" is safe. The fix is the usual Python pattern, None as the default:
is None checks whether a value is None. It's how Python programmers test for None, rather than == None.
Check what you learned
Four questions. Pick or type an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Tutorial: Keyword Arguments: keyword arguments, and *args and **kwargs in a def
- The Python Tutorial: Arbitrary Argument Lists
- The Python Tutorial: Default Argument Values: the warning that a default is worked out only once
- The Python Tutorial: Lambda Expressions
- The Python Tutorial: Python Scopes and Namespaces
- Built-in Functions: sorted
- Sorting Techniques: Key Functions
- Programming FAQ: Why are default values shared between objects?