Standard Library
Included with Python
os
json
datetime
pathlib
csv
mathAPIs allow different systems to exchange data.
import loads a module.
import module_nameimport mathresult = math.sqrt(16)
print(result)4.0After importing a module, access its functions with:
module.function()import random
number = random.randint(1, 10)Imports a specific item from a module.
from module_name import item_namefrom math import sqrt
result = sqrt(16)Now you can use sqrt() directly.
from math import sqrt, ceil, floorThen:
sqrt(16)
ceil(4.2)
floor(4.8)as gives an imported module or item a shorter name.
import pandas as pdThen:
df = pd.DataFrame()Another example:
import numpy as nppandas → pd
numpy → np
matplotlib.pyplot → pltAliases are not mandatory.
project/
├── main.py
└── calculator.pydef calculate_total(price, quantity):
return price * quantityfrom calculator import calculate_total
total = calculate_total(8500, 10)
print(total)85000def calculate_total(price, quantity):
return price * quantityimport calculator
total = calculator.calculate_total(8500, 10)Python files have a built-in variable called:
__name__A common pattern is:
if __name__ == "__main__":
main()def main():
print("Program started")
if __name__ == "__main__":
main()This means: Run main() when this file is executed directly.
Some modules are not included with Python. They must be installed first.
pip install requestsThen:
import requestsExamples of third-party packages:
Included with Python
os
json
datetime
pathlib
csv
mathInstalled separately
requests
pandas
numpy
fastapiimport something_missingMay cause:
ModuleNotFoundErrorCommon reasons: