Modules and import
A module is a .py file. import math runs math.py once (top to bottom), then gives you a module object whose attributes are everything the file defined. Any file you write is a module too — import helpers looks for helpers.py next to your script, then along sys.path.
You should see
1.4142135623730951
3
Thursday
[('i', 4)]
module json
['load', 'loads']random and print five random integers between 1 and 6. Then from random import randint and do it again.Avoid
from os.path import *— pulls in unknown names, shadows your own- Importing inside a loop
- Importing a module for one constant you could copy
Prefer
import osthenos.path.join(...)— the reader sees where it came from- All imports at the top: standard library, then third-party, then your own
from x import yfor a few names you use constantly
ModuleNotFoundError: No module named 'requests'
import requests
print(requests.get("https://example.com").status_code)Traceback (most recent call last):
File "your code", line 1, in <module>
import requests
ModuleNotFoundError: No module named 'requests'Python searched every directory on sys.path and found no requests. Three causes, in order of likelihood: (1) the package is not installed in this interpreter — you installed it in a different Python or a different virtual environment; (2) a typo in the name; (3) your own module is not on the path. In this browser page, only the standard library and a few bundled packages exist — the same error you would get on a fresh machine.
Install it into the environment you are running: python3 -m pip install requests. Using python3 -m pip instead of bare pip guarantees the same interpreter.
