Modules and Imports
A module is a file containing Python definitions. Importing a module executes it once and binds the resulting namespace to a name, making its contents available. The standard library provides several hundred modules, and the scientific libraries used in this course are distributed the same way.
4.0 10.0
Forms of import
import x binds the module name, and its contents are reached through it as
x.name. This keeps the origin of every name visible at the point of use,
which matters when several modules define similarly named functions.
from x import y binds y directly, which is shorter but discards that
information. import x as z binds an alias; the scientific libraries have
conventional aliases (numpy as np, pandas as pd) that are used almost
universally and should be followed.
2 4.0 2
Avoid from x import *. It binds every public name in the module, which
obscures where each name came from and can silently replace an existing
variable.
Useful standard library modules
statistics provides mean, median and standard deviation. collections
provides specialised containers, of which Counter is the most immediately
useful. pathlib handles filesystem paths, and csv reads delimited files
with correct quoting.
24.8 30
Counter({'T': 4, 'A': 3, 'G': 3, 'C': 2})
statistics.mean returns an exact value for integer input where possible, so
its result may be an int or a Fraction rather than a float. Round or
convert explicitly when a specific type is required.
Import cost and placement
A module is executed on first import only; later imports of the same module reuse the cached result. Placing imports at the top of a file is the convention and makes a file's dependencies visible at a glance.
The name guard
When a file is executed directly, its __name__ is set to "__main__". When it
is imported, __name__ is the module's name. Guarding executable code with a
test on __name__ allows a file to serve both as a runnable script and as an
importable module, without the script's actions running on import.
running as a script
Every exercise in this course uses that guard, which is why the exercise code runs when tested but its functions can still be imported and checked individually.
Task
Write stats_line(values). Use the statistics module. Return
"n=<count> mean=<mean> median=<median>", with the mean and median each
rounded to two decimal places. An empty list returns "n=0".
Both statistics.mean and statistics.median raise StatisticsError on an
empty sequence, so the empty case must be handled before either is called.
Test cases · 3
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | 30 12 45 7 | n=4 mean=23.5 median=21.0 |
| 2 | stdin | 10 20 | n=2 mean=15 median=15.0 |
| 3 | stdin | · | n=0 |
Hints · 2
01Hint
statistics.mean and statistics.median both raise on an empty list.
02Hint
Round each value separately before putting it in the f-string.