import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
4.0
3.141592653589793
📦 Python comes with many built-in modules and also allows you to use external packages. To use code from other modules or libraries, you use import statements.
import
a ModuleImport the whole module and access functions or classes with dot notation.
from ... import ...
Import specific parts (functions, classes, variables) from a module directly.
as
Use as
to give a module or function an alias—useful for shortening long names.
*
)Import everything from a module (not recommended in most cases).
Avoid using *
in production code—it can pollute your namespace and create conflicts.
You can also import your own .py
files as modules.
Suppose you have a file myutils.py
:
You can import and use it:
You can import modules inside functions or conditionally.
Some frequent errors encountered when dealing with Import Statements in Python.
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) Cell In[9], line 1 ----> 1 import notamodule ModuleNotFoundError: No module named 'notamodule'