Lesson 2 of 3
Pass information to functions in flexible ways: positional and keyword arguments, default values, and collections as arguments.
About 25 minutes
By default, arguments are matched to parameters by position: the first argument goes to the first parameter, the second to the second, and so on. This is short and convenient, but you must remember the correct order. Swapping two arguments gives a wrong answer without any error.
def density(mass_g, volume_cm3): return mass_g / volume_cm3print(density(27.0, 10.0)) # correct orderprint(density(10.0, 27.0)) # swapped: wrong, but no error!You can also name each argument when you call the function, using parameter_name=value. These are keyword arguments. Order no longer matters, and the call documents itself, which helps when a function has several numeric parameters that are easy to mix up.
def density(mass_g, volume_cm3): return mass_g / volume_cm3print(density(volume_cm3=10.0, mass_g=27.0))You can mix both styles, but positional arguments must come first. density(27.0, volume_cm3=10.0) is fine; density(mass_g=27.0, 10.0) is a SyntaxError.
A parameter can have a default value, written parameter=value in the definition. If the caller leaves that argument out, the default is used. Defaults are ideal for settings that are usually the same, such as standard conditions or the number of decimal places. Parameters with defaults must come after those without.
Thermal expansion: a bar's change in length is ΔL = αL₀ΔT. The default expansion coefficient is copper's.
def expansion(length_m, temperature_change, alpha=16.5e-6): """Change in length (m). alpha is the expansion coefficient in 1/K (default: copper).""" return alpha * length_m * temperature_changeprint(f"Copper: {expansion(2.0, 80) * 1000:.3f} mm")print(f"Aluminium: {expansion(2.0, 80, alpha=23.1e-6) * 1000:.3f} mm")print(f"Invar: {expansion(2.0, 80, alpha=1.2e-6) * 1000:.3f} mm")An argument can be any value, including a list or a dictionary. This lets one function process a whole dataset or a whole record.
def summarise(values, unit=""): mean = sum(values) / len(values) print(f"n = {len(values)}, mean = {mean:.2f} {unit}, range = {min(values)} to {max(values)} {unit}")summarise([152, 160, 158, 149, 155], unit="HV")summarise([8.94, 8.97, 8.95])Functions can change the lists you pass in
append() or changes an item, the caller's list changes too. This can be useful, but if you don't intend it, work on a copy inside the function.Calling a function with too few or too many arguments raises a TypeError that names the problem. Run this example to see the message.
def density(mass_g, volume_cm3): return mass_g / volume_cm3print(density(27.0))The message density() missing 1 required positional argument: 'volume_cm3' tells you exactly which argument is missing.
Choose an answer and press Check answer. You can retry as often as you like.