Python course / Foundations
Functions
Turn a long script into named functions that take arguments and hand answers back. The default argument that quietly fills up between calls is the trap that catches everyone exactly once.
- arguments
- defaults
- return vs print
- scope
- *args and **kwargs
- recursion
- docstrings
- one job each
Runs in your browser. Start straight away; create an account when you want your progress kept.
def clean(name):
"""Tidy the spacing and normalise the case of a name."""
return " ".join(name.split()).title()
def initials(name, separator="."):
return separator.join(part[0] for part in name.split())
person = clean(" ada lovelace ")
print(person)
print(initials(person))
print(initials(person, separator=" "))
Ada Lovelace A.L A L
What you will learn
- Give a piece of code a name you can call.
- Pass values in, so one function serves many cases.
- Tell the difference between showing a value and handing it back.
- Let a caller leave out what usually stays the same.
- Say what a function does, in its name and in a sentence.
- Build a function and hand it back.
The lessons in this module
- Making a function
- Arguments
- return or print
- Returning early
- Default arguments
- Calling by name
- Functions calling functions
- Names inside a function
- Changing what you were passed
- The default that remembers
- Functions as values
- Functions made in a loop
- Naming and docstrings
- One job per function
- Any number of arguments
- Any number of named arguments
- Unpacking at the call
- A function that calls itself
- Building a list in a function
- Functions inside functions
- Checking the arguments
- Same arguments, same answer
- Arguments that must be named
- The shape of the answer
- A toolkit of text functions
- Functions over records
- Functions in a pipeline
- Checking your own functions
- A program made of functions
- Tier review: the duty roster
Ready when you are
Previous: Dictionaries, sets, tuples. Next: Errors and exceptions. All modules are on the course page.