A module in Python is simply a file that contains Python code such as functions, classes, and variables. Modules help you:
.py file containing Python code (functions, classes, variables).math, random).import statement to bring in functionality.as to give a shorter name to a module.Common ways to import and use modules in Python:
import module_namemodule_name.function().from module_name import name1, name2name1().import module_name as aliasalias.function().mymodule.py and then do import mymodule in another file.
# Importing the math module
import math
print(math.sqrt(16)) # Output: 4.0
from math import pi, pow
print(pi) # Output: 3.141592653589793
print(pow(2, 3)) # Output: 8.0
import math as m
print(m.sqrt(25)) # Output: 5.0
Save your reusable functions in one file and import them into another file.
# mymodule.py
def greet(name):
return f"Hello, {name}!"
# main.py
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!
math.sqrt(16) returns 4.0 using the square root function from the math module.pi is a constant for π, and pow(2, 3) computes 2 to the power of 3, giving 8.0.import math as m lets you call m.sqrt(25) instead of math.sqrt(25).greet is defined in mymodule.py, imported in main.py, and prints Hello, Alice!.import numpy as np).from module import function when you only need a few specific functions.from module import * in larger projects, as it can clutter the namespace.numpy or pandas and observe how it simplifies your code.from module import function vs import module and see how the function calls differ.mymodule.py with a few helper functions and reuse it across different small projects.