Import module in Python (original) (raw)

In Python, modules help organize code into reusable files. They allow you to import and use functions, classes and variables from other scripts. The import statement is the most common way to bring external functionality into your Python program.

Python modules are of two types: **built-in (come with Python) module and **external modules like pandas and numpy, which need to be installed separately.

Importing built-in Module

Built-in modules can be directly imported using "import" keyword without any installtion. This allows access to all the functions and variables defined in the module.

Python `

import math pie = math.pi print("Value of pi:", pie)

`

Output

Value of pi: 3.141592653589793

**Explanation:

Importing External Modules

To use external modules, we need to install them first, we can easily install any external module using pip command in the terminal, for example:

pip install module_name

Make sure to replace "module_name" with the name of the module we want to install, example: pandas, numpy, etc.

After installation, we can import the module like a regular built-in module using "import statement".

Python `

import pandas

Create a simple DataFrame

data = { "Name": ["Elon", "Trevor", "Swastik"], "Age": [25, 30, 35] }

df = pandas.DataFrame(data) print(df)

`

Output

  Name  Age

0 Elon 25 1 Trevor 30 2 Swastik 35

**Explanation:

Importing Specific Functions

Instead of importing the entire module, we can import only the functions or variables we need using the from keyword. This makes the code cleaner and avoids unnecessary imports.

Python `

from math import pi print(pi)

`

**Explanation:

Importing Modules with Aliases

To make code more readable and concise, we can assign an alias to a module using **as keyword. This is especially useful when working with long module names.

Python `

import math as m result = m.sqrt(25) print("Square root of 25:", result)

`

Output

Square root of 25: 5.0

**Explanation:

Importing Everything from a Module (*)

Instead of importing specific functions, we can import all functions and variables from a module using the * symbol. This allows direct access to all module contents without prefixing them with the module name.

Python `

from math import * print(pi) # Accessing the constant 'pi' print(factorial(6)) # Using the factorial function

`

Output

3.141592653589793 720

**Explanation:

Handling Import Errors in Python

When importing a module that doesn’t exist or isn't installed, Python raises an ImportError. To prevent this, we can handle such cases using try-except blocks.

Python `

try: import mathematics # Incorrect module name print(mathematics.pi) except ImportError: print("Module not found! Please check the module name or install it if necessary.")

`

Output

Module not found! Please check the module name or install it if necessary.

**Explanation:

Why do we need to import modules?