Python import Statement
Python import Statement
In this tutorial, we will learn about the Python import statement. It is recommended that large programs be divided into modules. This way, programmers can easily understand each module separately instead of the entire program.
A Python module is a file containing Python functions, definitions, and statements. Its filename ends with the extension *.py.
import statement
Python program typically begins with an import statement, which allows you to use libraries and modules in your code. We use the import keyword to import the definitions inside a module to another module or in the interactive interpreter.
Example
Import entire module
import math
This statement imports the math module containing various mathematical functions and constants. After importing it, you can access its functions directly with the math prefix. For example:
>>> # Python import statement Demo
>>>
>>> import math
>>>
>>> print(math.pi)
3.141592653589793
>>>
>>> # Python Tutorials – www.TestingDocs.com
The definitions inside the math module are available for use in the current program.For example, to compute the sine, you would use math.sin(number).
Import with Alias
import numpy as np
This statement imports the popular library for numerical operations, the NumPy library, and gives it the alias np. This alias allows you to use the library’s functions and classes with the np prefix. For example, to create a NumPy array, you would use np.array().
from keyword
The from…import keyword imports specific functions, classes, or variables from a module. This way, you don’t have to import the entire module, which can be more efficient if you only need a small part of it.
Basic syntax
from module_name import function_name
Example
from math import sqrt
The import statement is a fundamental command in Python. It enables code reuse and modular programming. You can leverage an extensive ecosystem of standard libraries and third-party modules in Python programs by importing modules.
—
Python Tutorials
Python Tutorial on this website can be found at:
More information on Python is available at the official website: