Modules & packages (concept)

Computer Science · Python

Question 1 of 10

0

    When a module that was already imported is imported again in the same program, Python:

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Modules & packages (concept) explained

    A module is a single Python file whose functions and variables can be used by other code, and a package is a folder of modules. Splitting a program into modules keeps related code together and lets you reuse it in several programs.

    You bring a module in with import. After import math you call math.sqrt, where the dot shows that the name belongs to the module. from math import sqrt brings in just that one name. Python looks for modules in the folder of the running script, in the standard library and in installed packages. A module inside a package is imported with a dotted path such as shop.pricing. Do not name your own file after a standard library module, such as random.py, because Python will import your file by mistake.

    # pricing.py
    TAX = 0.2
    
    def with_tax(price):
        return price * (1 + TAX)
    
    # main.py
    from pricing import with_tax
    print(with_tax(50))
    

    Worked example

    main.py imports with_tax from pricing.py. TAX is 0.2, so with_tax(50) computes 50×(1+0.2)=50×1.250 \times (1 + 0.2) = 50 \times 1.2. The result is 6060, so print displays 60.0, since Python shows a float for the multiplication.

    What you will practise

    104 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • A module in Python is:
    • The import statement:
    • A package is:
    • The standard library:
    • Importing a module runs:
    • Which statement imports only the sqrt function from the math module?
    • What does import math as m allow you to do?
    • Which file name extension is used for a Python source file?

    …and 96 more.