Functions
A function groups a sequence of statements under a name so that it can be
invoked repeatedly with different inputs. Defining a function creates an object
bound to that name; calling it executes the body and returns a value. A
function whose body completes without executing a return statement returns
None.
0.6666666666666666
Parameters and arguments
Parameters are the names in the definition; arguments are the values supplied at the call. Arguments may be passed by position, in the order the parameters are declared, or by keyword, naming the parameter explicitly. Keyword arguments are clearer at the call site when a function takes several parameters of the same type, and they may be given in any order.
A parameter with a default value may be omitted. Parameters with defaults must follow those without.
TP53 120 pass TP53 25 pass EGFR 45 pass
Default arguments are evaluated once
A default value is evaluated a single time, when the def statement executes,
not on each call. If the default value is a mutable object, such as a list or a dictionary, every call omitting that argument references and mutates the shared object instance across invocations.
['TP53'] ['TP53', 'BRCA1']
The established remedy is to default the parameter to None and construct the
mutable value inside the body, which produces a new object per call.
['TP53'] ['BRCA1']
Returning multiple values
A return statement listing several expressions returns a tuple, which unpacks
into separate names on assignment. This is the standard way to return a small,
fixed set of related results.
12 45
Arguments are passed by reference
Parameters are bound to the same objects the caller passed. Rebinding a parameter inside the function has no effect on the caller, but mutating a mutable argument does. A function that modifies its arguments should say so in its docstring, or return a new value instead.
[1, 2] [1, 2, 0]
Docstrings
A string literal as the first statement of a function is its docstring,
retrievable through help() and __doc__. State what the function returns and
any condition on its inputs.
Task
Write summarise(depths). It receives a list of integers and returns a tuple
of (count, minimum, maximum, mean), with the mean rounded to two decimal
places. An empty list returns (0, 0, 0, 0.0).
Handle the empty case before calling min or max, both of which raise
ValueError on an empty sequence.
Test cases · 3
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | 30 12 45 7 | (4, 7, 45, 23.5) |
| 2 | stdin | 10 | (1, 10, 10, 10.0) |
| 3 | stdin | · | (0, 0, 0, 0.0) |
Hints · 2
01Hint
Handle the empty list first, before calling min() or max().
02Hint
round(total / count, 2) gives the rounded mean.