The import
statement in Python is used to include external modules, libraries, or specific functionalities into your program. It allows you to access pre-written code and avoid rewriting common functionality.
Example
import math
# Use the sqrt function from the math module
result = math.sqrt(16)
print(result)
Output:
4.0
Syntax
import module_name
You can also import specific items from a module:
from module_name import item_name
Or rename the module or item for convenience:
import module_name as alias_name
from module_name import item_name as alias_name
Why Use import?
- Access Built-in Modules: Python provides a wide range of built-in modules like math, random, and datetime to simplify complex tasks.
- Reuse Code: Import your own or external libraries to avoid redundancy.
- Modular Programming: Enables splitting large programs into smaller, reusable modules.
- Community Libraries: Leverage powerful third-party libraries like numpy, pandas, and requests.
Common Examples
1. Importing the Entire Module
import random
# Generate a random number between 1 and 10
number = random.randint(1, 10)
print(number)
Output:
A random number between 1 and 10 (e.g., 7)
2. Importing Specific Items
from math import pi, sqrt
# Use the imported pi and sqrt
print(pi) # Output: 3.141592653589793
print(sqrt(25)) # Output: 5.0
3. Importing with an Alias
import datetime as dt
# Get the current date and time
now = dt.datetime.now()
print(now)
Output:
2025-01-11 12:30:45.123456 (Current date and time)
4. Importing All Items
from math import *
# Use various math functions without prefixing with 'math.'
result = sin(pi / 2)
print(result)
Output:
1.0
5. Importing a Custom Module
Custom Module: greetings.py
def hello(name):
return f"Hello, {name}!"
Main Program:
from greetings import hello
print(hello("Alice"))
Output:
Hello, Alice!
Key Notes
- Module Search Path: Python looks for modules in specific directories. Use
sys.path
to see where Python searches. - Avoid
import *
: Usingfrom module import *
can lead to namespace pollution and conflicts. - Use Aliases: Aliases make imports shorter and more readable, especially for long module names.
- Install Third-Party Modules: Use
pip
installmodule_name
to install external libraries.
By understanding and using the import
statement effectively, you can create modular, efficient, and reusable Python programs!