Python import

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?

  1. Access Built-in Modules: Python provides a wide range of built-in modules like math, random, and datetime to simplify complex tasks.
  2. Reuse Code: Import your own or external libraries to avoid redundancy.
  3. Modular Programming: Enables splitting large programs into smaller, reusable modules.
  4. 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

  1. Module Search Path: Python looks for modules in specific directories. Use sys.path to see where Python searches.
  2. Avoid import *: Using from module import * can lead to namespace pollution and conflicts.
  3. Use Aliases: Aliases make imports shorter and more readable, especially for long module names.
  4. Install Third-Party Modules: Use pip install module_name to install external libraries.

By understanding and using the import statement effectively, you can create modular, efficient, and reusable Python programs!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top