← Python from Scratch Lesson 51 of 78 · 10 XP

Modules and import

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A module is a file of Python code that you can plug into your program. Python comes with a huge standard library: hundreds of ready-made modules.

Ways to import:

import math                   # the whole module, accessed with a dot
math.sqrt(16)                 # 4.0

from math import sqrt, pi     # only the names you need
sqrt(16)

import statistics as st       # your own short name
st.mean([1, 2, 3])            # 2

Your own module is just a file. If there's a helpers.py next to your program with a function hello(), you can import it with from helpers import hello.

Modules often contain this check:

if __name__ == "__main__":
    main()

The code inside runs only if the file is run directly, not imported with import.

A few modules useful every day: math, random, datetime, json, re, os, collections, statistics.

Task. Write a function median_of(nums) that returns the median of a list — the value "in the middle" after sorting. Use the median function from the statistics module.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.