πŸŽ“ Velnov

🐍 Python · Topic 13 of 20

Modules & Packages β€” Python Questions with Answers

Start with the study notes on Modules & Packages (definitions, examples and a quick revision), then work through 30 practice questions, each with the correct answer and a clear explanation of why it is right. When you are ready, take this topic as an interactive quiz to test yourself.

12 easy Β· 13 medium Β· 5 hard Β· Part of Python: Master Python from basics to advanced - 20 topics.

Topic overview

Modules and Packages – reusing code

1. Modules and import

A module is a .py file whose functions and variables you can reuse with import.

import math
from math import sqrt
print(math.sqrt(16), sqrt(25))
print(math.floor(2.7), math.ceil(2.1))
print(round(math.pi, 4))
Output4.0 5.0
2 3
3.1416

2. The standard library

The standard library is the set of modules that come with Python, with nothing to install.

import statistics
from collections import Counter
print(statistics.mean([80, 90, 100]))
print(statistics.median([1, 3, 99]))
print(Counter("banana"))
Output90
3
Counter({'a': 3, 'n': 2, 'b': 1})

random

import random
dice = random.randint(1, 6)          # 1 to 6, BOTH included
winner = random.choice(["Ana", "Ben", "Cy"])
x = random.random()                  # 0.0 up to (not including) 1.0

3. pip and third-party packages

pip installs packages from PyPI (the Python Package Index). You run it in the terminal, not inside Python.

Remember: Importing something that isn't installed raises ModuleNotFoundError.

4. Your own modules

Any .py file you write is a module too. If helpers.py sits next to main.py, then main.py can import helpers.

# helpers.py
def greet(name):
    return f"Hello {name}"

# main.py
import helpers
print(helpers.greet("Ana"))

Remember: Importing a module runs its top-level code, but only on the first import. Python caches it after that.

5. if __name__ == "__main__":

Python sets __name__ to "__main__" in the file you run directly, and to the module's name when it is imported. This guard runs code only when the file is run directly, not when it is imported.

def main():
    print("running as a script")

if __name__ == "__main__":
    main()
Outputrunning as a script

6. Packages

A package is a folder of modules, often with an __init__.py file.

# myapp/
#     __init__.py
#     utils.py
#     models.py

from myapp import utils
from myapp.models import User

7. Where Python looks for modules

Python searches the running script's folder first, then the folders in sys.path (the standard library, then installed packages).

Remember: If you name your own file random.py, it shadows the real random module and import random breaks. Never name files after standard modules.

Examples:

  • sys.argv holds command-line arguments: python app.py Ana gives ['app.py', 'Ana'].
  • A circular import happens when two modules import each other. Fix it by moving the shared code to a third module.

8. Import style (PEP 8)

Put imports at the top of the file, in three groups separated by blank lines: standard library, then third-party, then your own modules.

import os
import json

import requests

from myapp import helpers

9. Common misconceptions

MisconceptionCorrect understanding
random.randint(1, 6) never gives 6.randint includes both ends; it can give 6.
from math import * is the cleanest import.It hides where names come from and can overwrite yours.
Importing a module twice runs it twice.Python caches modules; top-level code runs only on the first import.
You run pip inside the Python shell.pip runs in the terminal.
A file called random.py is harmless.It shadows the real random module.

10. Quick revision

Module
A .py file you can import.
Package
A folder of modules.
Alias
import numpy as np.
Standard library
Modules that come with Python.
pip
Installs packages from PyPI.
requirements.txt
Lists a project's packages.
__name__ == "__main__"
True only when the file is run directly.
sys.path
The folders Python searches for modules.

11. Test your understanding

  1. After import math, how do you call the square root?

    Show answer

    math.sqrt(16)

  2. What does from math import sqrt let you write?

    Show answer

    sqrt(16), without the math. prefix.

  3. What range does random.randint(1, 6) cover?

    Show answer

    1 to 6, both included.

  4. What is pip?

    Show answer

    Python's package installer, which downloads packages from PyPI.

  5. What does if __name__ == "__main__": do?

    Show answer

    Runs code only when the file is run directly, not when it is imported.

  6. What is a package?

    Show answer

    A folder of modules.

  7. Why does naming your file random.py break import random?

    Show answer

    Your file shadows the standard random module.

  8. Which exception does importing a missing module raise?

    Show answer

    ModuleNotFoundError.

Key takeaway: Import what you need from the standard library, install extras with pip, split your project into modules, and guard script code with __name__.

Notes written by Velnov. Every code example with an output was run in Python 3 to check that the output shown is exactly what Python prints.

Key concepts in this topic

importCode reuseNamespacesfrom-importAliasesConventionsBest practicesrandom modulerandint vs randrangechoice()sample()shuffle()random()uniform()math moduleRoundingdatetime moduletime modulePyPIThird-party packagesBatteries includedpipCustom modulesProject structure

Jump to: Easy Β· Medium Β· Hard

Easy questions (12)

Q1. easy

What is a module in Python?

  1. A A .py file whose functions/variables you can import and reuse
  2. B A type of loop
  3. C A compressed archive
  4. D A class method

Answer: A β€” A .py file whose functions/variables you can import and reuse

Any Python file is a module. import makes its functions, classes and variables available in your code - the basic unit of code reuse.

importCode reuse

Q2. easy

After 'import math', how do you call its square root function?

import math
print(math.sqrt(16))   # 4.0
print(math.pi)          # 3.141592653589793
  1. A math.sqrt(16)
  2. B sqrt(16)
  3. C math->sqrt(16)
  4. D import sqrt(16)

Answer: A β€” math.sqrt(16)

Plain import binds the MODULE name - you access contents with the dot: math.sqrt(16). Bare sqrt(16) only works after 'from math import sqrt'.

importNamespaces

Q3. easy

What does 'from math import sqrt' let you write?

from math import sqrt, pi
print(sqrt(16))   # 4.0
print(pi)          # 3.14159...
  1. A sqrt(16) - directly, without the math. prefix
  2. B math.sqrt(16) only
  3. C Nothing - it's invalid
  4. D sqrt.math(16)

Answer: A β€” sqrt(16) - directly, without the math. prefix

from-import copies a specific name into your file's namespace: sqrt(16) works directly. The rest of math stays unimported (math.pi would be a NameError).

from-import

Q4. easy

What does 'import numpy as np' do?

import numpy as np
import pandas as pd
arr = np.array([1, 2, 3])
  1. A Imports numpy under the shorter alias np
  2. B Imports only the np part of numpy
  3. C Renames the numpy package on disk
  4. D Creates a copy of numpy

Answer: A β€” Imports numpy under the shorter alias np

as creates an alias - the module is used as np.array(...) instead of numpy.array(...). Common conventions: numpy as np, pandas as pd.

AliasesConventions

Q6. easy

What does random.randint(1, 6) return?

import random
dice = random.randint(1, 6)   # 1,2,3,4,5 or 6
  1. A A random integer from 1 to 6, BOTH ends included - like a dice roll
  2. B 1 to 5 (6 excluded)
  3. C A random float
  4. D Always 6

Answer: A β€” A random integer from 1 to 6, BOTH ends included - like a dice roll

randint is INCLUSIVE on both ends - unusual for Python (range excludes its stop!). Perfect dice: random.randint(1, 6).

  • Contrast: random.randrange(1, 6) gives 1-5.

random modulerandint vs randrange

Q7. easy

Which picks ONE random item from a list?

import random
winner = random.choice(["Ana", "Ben", "Cy"])
print(winner)
  1. A random.choice(items)
  2. B random.pick(items)
  3. C items.random()
  4. D random.one(items)

Answer: A β€” random.choice(items)

random.choice(sequence) returns one random element. Related: random.sample(items, 3) picks 3 without repeats; random.shuffle(items) reorders the list in place.

choice()sample()shuffle()

Q9. easy

What do math.floor(2.7) and math.ceil(2.1) return?

import math
print(math.floor(2.7))   # 2
print(math.ceil(2.1))    # 3
  1. A 2 and 3
  2. B 3 and 2
  3. C 2.7 and 2.1
  4. D 3 and 3

Answer: A β€” 2 and 3

floor() rounds DOWN to the nearest integer (2.7 -> 2), ceil() rounds UP (2.1 -> 3). Both return ints.

math moduleRounding

Q10. easy

How do you get today's date?

from datetime import date, datetime
print(date.today())      # 2026-07-03
print(datetime.now())    # 2026-07-03 14:30:05.123
  1. A from datetime import date; date.today()
  2. B import today
  3. C time.today()
  4. D date.now.today

Answer: A β€” from datetime import date; date.today()

The datetime module handles dates and times: date.today() gives the current date; datetime.now() adds the time of day.

datetime module

Q11. easy

Which pauses the program for 2 seconds?

import time
print("3...")
time.sleep(1)
print("2...")
  1. A time.sleep(2)
  2. B time.wait(2)
  3. C sleep.time(2)
  4. D pause(2)

Answer: A β€” time.sleep(2)

time.sleep(seconds) blocks execution for that long - used for delays, animations, rate limiting.

time module

Q12. easy

What is pip?

# in the terminal (not in Python!):
pip install requests
pip list            # show installed packages
  1. A Python's package installer - downloads third-party libraries from PyPI
  2. B A Python IDE
  3. C A file format
  4. D Python's debugger

Answer: A β€” Python's package installer - downloads third-party libraries from PyPI

pip installs packages from the Python Package Index (PyPI): pip install requests. The standard library needs no installing; pip is for everything beyond it.

PyPIThird-party packages

Q21. easy

Which computes the average of [80, 90, 100] using the standard library?

import statistics
print(statistics.mean([80, 90, 100]))    # 90
print(statistics.median([1, 3, 99]))      # 3
  1. A statistics.mean([80, 90, 100])
  2. B math.average([80, 90, 100])
  3. C avg([80, 90, 100])
  4. D numpy only can do this

Answer: A β€” statistics.mean([80, 90, 100])

The statistics module has mean, median, mode, stdev - no installation needed. (math has no average function; numpy works too but isn't required.)

statistics module

Q28. easy

Which command shows every package pip has installed?

  1. A pip list
  2. B pip show all
  3. C python --packages
  4. D pip everything

Answer: A β€” pip list

pip list prints installed packages and versions. pip show <name> gives details of one; pip freeze outputs the requirements.txt format.

piprequirements.txt

Medium questions (13)

Q5. medium

Why is 'from math import *' discouraged?

# unclear:
from math import *
print(floor(2.7))    # where's floor from?

# clear:
import math
print(math.floor(2.7))
  1. A It dumps EVERY name into your file - unclear origins, and it can silently overwrite your own variables
  2. B It's slower to run
  3. C It's a syntax error
  4. D It only imports half the module

Answer: A β€” It dumps EVERY name into your file - unclear origins, and it can silently overwrite your own variables

Star imports pollute the namespace: readers can't tell where a function came from, and two star imports can clash (both defining e.g. sqrt). Import what you need, explicitly.

NamespacesBest practices

Q8. medium

What does random.random() return?

import random
print(random.random())        # e.g. 0.7134...
print(random.uniform(1, 10))  # float between 1 and 10
  1. A A float from 0.0 up to (but not including) 1.0
  2. B A random integer
  3. C 0 or 1
  4. D A float from -1 to 1

Answer: A β€” A float from 0.0 up to (but not including) 1.0

random.random() gives a float in [0.0, 1.0). Scale it for other ranges, or use random.uniform(a, b) directly.

random()uniform()

Q13. medium

What is the STANDARD LIBRARY?

  1. A The modules that ship WITH Python - math, random, os, json... no pip needed
  2. B Any code on GitHub
  3. C Packages you must pay for
  4. D Only the built-in functions like print

Answer: A β€” The modules that ship WITH Python - math, random, os, json... no pip needed

Python comes 'batteries included': hundreds of ready modules (math, random, datetime, os, json, csv, sqlite3...) available to import immediately. Third-party packages (numpy, requests) are the ones pip installs.

Batteries includedpip

Q14. medium

You wrote helpers.py with a function greet(). How does main.py (same folder) use it?

# helpers.py
def greet(name):
    return f"Hello {name}"

# main.py
import helpers
print(helpers.greet("Ana"))
  1. A import helpers, then helpers.greet()
  2. B include helpers.py
  3. C using helpers
  4. D You can't import your own files

Answer: A β€” import helpers, then helpers.greet()

Your own .py files are modules too! import helpers (no .py extension) loads the file; call its contents with the dot. This is how projects split into multiple files.

Custom modulesProject structure

Q17. medium

Which exception does 'import nosuchmodule' raise?

try:
    import numpy
except ModuleNotFoundError:
    print("run: pip install numpy")
  1. A ModuleNotFoundError
  2. B FileNotFoundError
  3. C NameError
  4. D KeyError

Answer: A β€” ModuleNotFoundError

Importing something that isn't installed or doesn't exist raises ModuleNotFoundError (a subclass of ImportError). Usually the fix: pip install it, or check the spelling.

ModuleNotFoundErrorpip

Q18. medium

What does dir(math) show?

import math
print(dir(math))
# ['ceil', 'cos', 'floor', 'pi', 'sqrt', ...]
  1. A Every name (functions, constants) defined in the math module
  2. B The folder containing math
  3. C The math source code
  4. D Math homework

Answer: A β€” Every name (functions, constants) defined in the math module

dir(anything) lists its attributes - for a module, all its functions and constants. Great for exploring: dir(str), dir(list), dir(random).

dir()help()Exploration

Q19. medium

What is the os module mainly for?

import os
print(os.getcwd())          # current folder
print(os.listdir("."))     # files in it
os.makedirs("output", exist_ok=True)
  1. A Talking to the operating system - files, folders, paths, environment variables
  2. B Object serialization
  3. C Online services
  4. D Optimizing speed

Answer: A β€” Talking to the operating system - files, folders, paths, environment variables

os (and its friend os.path, plus the modern pathlib) handles OS tasks: list folders (os.listdir), make dirs (os.makedirs), check paths, read environment variables.

os modulepathlib

Q20. medium

What does collections.Counter do? Counter(["a", "b", "a", "a"])

from collections import Counter
votes = ["ana", "ben", "ana", "ana"]
c = Counter(votes)
print(c)                  # Counter({'ana': 3, 'ben': 1})
print(c.most_common(1))   # [('ana', 3)]
  1. A Counts occurrences: Counter({'a': 3, 'b': 1})
  2. B Counts to infinity
  3. C Removes duplicates
  4. D Sorts the list

Answer: A β€” Counts occurrences: Counter({'a': 3, 'b': 1})

Counter is a dict subclass that counts items in one line - replacing the manual get(x, 0) + 1 loop. Bonus: .most_common(n) gives the top n.

Countercollections module

Q24. medium

You named your script random.py and 'import random' now breaks. Why?

  1. A Your own file shadows the standard random module - Python imports YOUR file instead
  2. B random was removed from Python
  3. C You must restart the computer
  4. D randint is Python 2 only

Answer: A β€” Your own file shadows the standard random module - Python imports YOUR file instead

The script's own folder is FIRST on the import path, so random.py (yours) wins over the standard library. Symptoms: AttributeError: module 'random' has no attribute 'randint'. Fix: rename your file.

Shadowingsys.path

Q25. medium

What does sys.argv contain?

import sys
# python app.py Ana
print(sys.argv)        # ['app.py', 'Ana']
print(sys.argv[1])     # Ana
  1. A The command-line arguments: sys.argv[0] is the script name, the rest are user-supplied
  2. B All environment variables
  3. C The Python version
  4. D System errors

Answer: A β€” The command-line arguments: sys.argv[0] is the script name, the rest are user-supplied

Running 'python app.py hello 42' gives sys.argv = ['app.py', 'hello', '42'] - all strings. It's the simplest way to accept command-line input.

sys moduleCommand line

Q26. medium

What does math.pi ** 2 compute, roughly?

import math
print(math.pi ** 2)     # 9.869...
area = math.pi * r**2   # circle area
  1. A 9.87 (pi squared)
  2. B 6.28 (2 pi)
  3. C 3.14
  4. D Error - pi is a function

Answer: A β€” 9.87 (pi squared)

math.pi is a CONSTANT (3.14159...), not a function - no parentheses. pi squared is about 9.87.

math constants

Q29. medium

What is requirements.txt used for?

# requirements.txt
requests==2.31.0
numpy>=1.24

# install everything:
pip install -r requirements.txt
  1. A Listing a project's package dependencies so others can 'pip install -r requirements.txt'
  2. B Python's TODO list
  3. C License requirements
  4. D The program's system requirements

Answer: A β€” Listing a project's package dependencies so others can 'pip install -r requirements.txt'

It records exactly what packages (and versions) a project needs. Anyone cloning your project runs one command to install them all - reproducible environments.

Dependenciespip

Q30. medium

Which import style does PEP 8 recommend at the TOP of a file?

import os
import json

import requests

from myapp import helpers
  1. A Standard library first, then third-party, then your own modules - in separate groups
  2. B Alphabetical single list, mixed
  3. C Imports go at the bottom
  4. D One giant from x import *

Answer: A β€” Standard library first, then third-party, then your own modules - in separate groups

PEP 8 groups imports: 1) standard library, 2) third-party, 3) local modules - blank line between groups, all at the top of the file. Readers instantly see what the file depends on.

PEP 8Code style

Hard questions (5)

Q15. hard

What is the purpose of: if __name__ == "__main__": main()

# helpers.py
def greet(): ...

if __name__ == "__main__":
    greet()   # runs only via: python helpers.py
              # NOT when: import helpers
  1. A Run main() only when the file is executed DIRECTLY - not when it's imported by another file
  2. B Declare the program's name
  3. C Make the file importable at all
  4. D It's required in every Python file

Answer: A β€” Run main() only when the file is executed DIRECTLY - not when it's imported by another file

Python sets __name__ to "__main__" in the file being run, but to the module's name when imported. The guard lets a file be BOTH a runnable script AND an importable library - imports get the functions without side effects.

  • A favorite interview question - know this one cold.

__name__Scripts vs modules

Q16. hard

print("loading!") sits at the TOP of helpers.py (outside any function). What happens on 'import helpers'?

# helpers.py
print("loading!")     # runs on import!
def greet(): ...

# main.py
import helpers   # prints: loading!
import helpers   # (cached - nothing prints)
  1. A It prints 'loading!' - top-level code RUNS at import time (but only on the first import)
  2. B Nothing - imports never execute code
  3. C SyntaxError
  4. D It prints on every import statement, even repeated ones

Answer: A β€” It prints 'loading!' - top-level code RUNS at import time (but only on the first import)

Importing EXECUTES the module top to bottom - defs create functions, and loose statements run. Python caches modules, so a second 'import helpers' does NOT re-run it. This is why the __main__ guard matters.

Import mechanicsModule caching

Q22. hard

What is a PACKAGE, as opposed to a module?

myapp/
  __init__.py
  utils.py
  models.py

# usage:
from myapp import utils
from myapp.models import User
  1. A A folder of modules (traditionally marked by an __init__.py file) - importable as package.module
  2. B A zip file
  3. C Any file over 1000 lines
  4. D A module with classes

Answer: A β€” A folder of modules (traditionally marked by an __init__.py file) - importable as package.module

Packages organize related modules into folders: myapp/utils.py imports as 'from myapp import utils'. __init__.py marks the folder as a package (optional since 3.3 but still common) and runs on package import.

Packages__init__.py

Q23. hard

Where does Python LOOK for modules when you import?

import sys
print(sys.path)
  1. A The script's folder, then the paths in sys.path (standard library, installed packages)
  2. B The whole hard drive
  3. C Only the standard library
  4. D The internet

Answer: A β€” The script's folder, then the paths in sys.path (standard library, installed packages)

Python walks sys.path in order: the running script's directory first, then standard library locations, then site-packages (pip installs). This is why a local file named random.py can SHADOW the real random module - a classic bug!

  • Never name your files math.py, random.py, string.py...

sys.pathShadowingImport order

Q27. hard

What is a circular import?

  1. A a.py imports b.py while b.py imports a.py - one gets a half-loaded module and often crashes
  2. B Importing the same module twice
  3. C Importing with a loop
  4. D A pip feature

Answer: A β€” a.py imports b.py while b.py imports a.py - one gets a half-loaded module and often crashes

When two modules import each other, Python starts loading a, pauses to load b, which asks for a - but a is only half-executed, so names may be missing (ImportError/AttributeError). Fix: restructure, move shared code to a third module, or import inside functions.

Circular importsArchitecture

Practice β€œModules & Packages” as a quiz