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: use math.sqrt(16).
from math import sqrt: use sqrt(16) directly.
import numpy as np: an alias (a shorter name).
from math import * imports everything. Avoid it: names become unclear and can clash.
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.
math: square roots, rounding, pi.
random: random numbers and choices.
datetime and time: dates, times and pauses.
os and sys: files, folders and command-line arguments.
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.
pip install requests installs a package.
pip list shows what is installed.
requirements.txt lists a project's packages; pip install -r requirements.txt installs them all.
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.
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
Misconception
Correct 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
After import math, how do you call the square root?
Show answer
math.sqrt(16)
What does from math import sqrt let you write?
Show answer
sqrt(16), without the math. prefix.
What range does random.randint(1, 6) cover?
Show answer
1 to 6, both included.
What is pip?
Show answer
Python's package installer, which downloads packages from PyPI.
What does if __name__ == "__main__": do?
Show answer
Runs code only when the file is run directly, not when it is imported.
What is a package?
Show answer
A folder of modules.
Why does naming your file random.py break import random?
Show answer
Your file shadows the standard random module.
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.
A A .py file whose functions/variables you can import and reuse
B A type of loop
C A compressed archive
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
A math.sqrt(16)
B sqrt(16)
C math->sqrt(16)
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...
A sqrt(16) - directly, without the math. prefix
B math.sqrt(16) only
C Nothing - it's invalid
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])
A Imports numpy under the shorter alias np
B Imports only the np part of numpy
C Renames the numpy package on disk
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
A A random integer from 1 to 6, BOTH ends included - like a dice roll
B 1 to 5 (6 excluded)
C A random float
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)
A random.choice(items)
B random.pick(items)
C items.random()
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
A 2 and 3
B 3 and 2
C 2.7 and 2.1
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.
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...")
A time.sleep(2)
B time.wait(2)
C sleep.time(2)
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
A Python's package installer - downloads third-party libraries from PyPI
B A Python IDE
C A file format
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?
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?
A pip list
B pip show all
C python --packages
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))
A It dumps EVERY name into your file - unclear origins, and it can silently overwrite your own variables
B It's slower to run
C It's a syntax error
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
A A float from 0.0 up to (but not including) 1.0
B A random integer
C 0 or 1
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?
A The modules that ship WITH Python - math, random, os, json... no pip needed
B Any code on GitHub
C Packages you must pay for
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?
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.
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', ...]
A Every name (functions, constants) defined in the math module
B The folder containing math
C The math source code
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)
A Talking to the operating system - files, folders, paths, environment variables
B Object serialization
C Online services
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"])
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?
A Your own file shadows the standard random module - Python imports YOUR file instead
B random was removed from Python
C You must restart the computer
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
A The command-line arguments: sys.argv[0] is the script name, the rest are user-supplied
B All environment variables
C The Python version
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
A 9.87 (pi squared)
B 6.28 (2 pi)
C 3.14
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.
A Listing a project's package dependencies so others can 'pip install -r requirements.txt'
B Python's TODO list
C License requirements
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
A Standard library first, then third-party, then your own modules - in separate groups
B Alphabetical single list, mixed
C Imports go at the bottom
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
A Run main() only when the file is executed DIRECTLY - not when it's imported by another file
B Declare the program's name
C Make the file importable at all
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'?
A It prints 'loading!' - top-level code RUNS at import time (but only on the first import)
B Nothing - imports never execute code
C SyntaxError
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
A A folder of modules (traditionally marked by an __init__.py file) - importable as package.module
B A zip file
C Any file over 1000 lines
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)
A The script's folder, then the paths in sys.path (standard library, installed packages)
B The whole hard drive
C Only the standard library
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?
A a.py imports b.py while b.py imports a.py - one gets a half-loaded module and often crashes
B Importing the same module twice
C Importing with a loop
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.