CODING
ADVENTURE
0 / 12 completed

FIELD NOTE 09 / BEGINNER PYTHON

Python modules and imports: reuse a tool

A module groups reusable Python code. import makes that module available so your program can use its names.

The idea

You do not need to invent every tool in Tony’s workshop before using it. Likewise, Python’s standard library provides tools for numbers, text and structured data. Learn what goes in, what comes out and what assumptions a tool makes. The period in math.sqrt means “look up sqrt inside math”; it is not a decimal point in this context.

A tiny experiment

PYTHON 3PREDICT BEFORE YOU RUN
import math
import json

print(math.sqrt(81))
record = {"clues": 3, "checked": True}
print(json.dumps(record))
Run and change this example ↗
Reveal the expected output
9.0
{"clues": 3, "checked": true}

Read it one step at a time

  1. import math makes the math module available. sqrt returns a square root.
  2. json.dumps converts the record into JSON text, a format other programs can read.
  3. JSON spells true in lower case. Python spells its Boolean True with a capital T. They are different syntaxes.

Make one change

Change 81 to 100 and clues to 4. Predict both output lines.

Check your thinking

The first is 10.0. The JSON record contains "clues": 4.

Keep following the trail

Sources & further reading

Companion notes for Coding Adventure by James Colby. Historical claims link to their sources; the examples are written for this learning trail.