Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.1 — import: Using Code from Other Files
Python · Example 4 of 4

A real use: a shop's bill calculator in its own module

This is why modules exist. The tax rule lives in one file, billing.py. Every other file that needs a bill imports it, so the rate is changed in one place only. Here the file is written first so the example is self-contained.

import loads another module and gives you a name for it. Python runs the module's file once, the first time it is imported, and keeps the result in sys.modules so that every later import is instant and shares the same module object.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Import sqrt from math under the name root, then print root(144).

02

Write a program that imports json, then prints "json" in sys.modules (import sys too) and the module's name json.__name__.

03

Write a file shapes.py that sets SIDES = 4 and prints loading shapes. (Create it from your program with Path("shapes.py").write_text(...), as in the second example.) Import it twice and show that the message appears only once.

04

Import sys. Print "antigravity" in sys.modules. Then import the module colorsys (do not import antigravity) and print the same check again. Explain the two answers.

Explain it without notes

01

What exactly happens when Python executes import greeter for the first time?

02

What is sys.modules, and what does it explain?

03

What is the difference between import x and from x import name?

04

Why is from module import * discouraged?

A real use: a shop's bill calculator in its own module
Sign in to run this example in your browser.

Expected output

subtotal: 255.49
with GST: 301.48
rate used: 0.18