Python Fundamentals: Imports and Modules


Modules in Python are .py files that contain a collection of functions and variables. These can be imported into other Python files or IPython sessions to make use of those functionalities.

a. Importing a module: To import a module, you can use the 'import' statement.

Code

import math
print(math.sqrt(16))

Output

4.0

b. Using 'from...import' statement: If you need only certain functions or variables, you can selectively import them using the 'from...import' statement.

Code

from math import pi
print(pi)

Output

3.141592653589793

c. Using 'as' for aliasing: You can also use an alias for a module or a function while importing it.

Code

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

Output

[1 2 3 4 5]

d. Another example.

Code

import sys
from datetime import datetime as dt
print(sys.version)
print(dt.now())

Output

3.11.5 (tags/v3.11.5:cce6ba9, Aug 24 2023, 14:38:34) [MSC v.1936 64 bit (AMD64)]
2023-08-30 16:36:45.864908 

Enquiries

[email protected]

Copyright © 2023 - slash-root.com