What is a Module?

In Python, a module is a file that contains Python code. A module can define functions, classes, and variables. Modules are used to organize Python code into reusable and sharable components. Modules can be imported into other Python code, allowing developers to reuse code without having to copy and paste it.

Importing Modules

To use a module in your Python code, you need to import it. There are several ways to import a module in Python:

Method 1: import module_name

import math

print(math.pi)

Output:

3.141592653589793

In this example, we import the math module using the import statement. We then use the math module to print the value of the mathematical constant pi.

Method 2: import module_name as alias

import math as m

print(m.pi)

Output:

3.141592653589793

In this example, we import the math module using the import statement and give it an alias m. We then use the m alias to print the value of the mathematical constant pi.

Method 3: from module_name import function_name

from math import pi

print(pi)

Output:

3.141592653589793

In this example, we import the pi function from the math module using the from statement. We then use the pi function to print the value of the mathematical constant pi.

**Method 4: from module_name import ***