A module is a file of Python code. Importing one makes its contents available.
import math
print(math.sqrt(16))
print(math.log2(1024))
Import forms
import math
print(math.pi)
from math import sqrt, log2
print(sqrt(16), log2(8))
import statistics as stats
print(stats.mean([1, 2, 3]))
import x keeps the module name as a prefix, which makes it obvious where a
function came from. from x import y is shorter. Both are common; the alias
form (import numpy as np) is standard for the scientific libraries.
Avoid from math import *. It hides which names exist and can overwrite your
own variables.
Useful standard library modules
import statistics
import collections
depths = [30, 12, 45, 7, 30]
print(statistics.mean(depths))
print(statistics.median(depths))
print(collections.Counter("ATGGCC"))
collections.Counter counts occurrences and replaces the manual counting loop
from the dictionaries lesson.
name
When a file runs directly, its __name__ is "__main__". When it is imported,
__name__ is the module name. This is why scripts end with:
def main():
print("running")
if __name__ == "__main__":
main()
The code under that check runs when the file is executed, but not when another file imports it.
Task
Write stats_line(values). Use the statistics module. Return
"n=<count> mean=<mean> median=<median>", with mean and median each rounded to
2 decimals. Return "n=0" for an empty list.
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.