KnowledgeBoat Logo

Computer Science

Explain the difference between import <module> and from <module> import statements, with examples.

Python Libraries

8 Likes

Answer

import <module> statementfrom <module> import statement
It imports entire module.It imports single, multiple or all objects from a module.
To access one of the functions, we have to specify the name of the module and the name of the function, separated by a dot. This format is called dot notation. The syntax is : <module-name>.<function-name>()To access functions, there is no need to prefix module's name to imported item name. The syntax is : <function-name>
Imports all its items in a new namespace with the same name as of the module.Imports specified items from the module into the current namespace.
This approach does not cause any problems.This approach can lead to namespace pollution and name clashes if multiple modules import items with the same name.
For example:
import math
print(math.pi)
print(math.sqrt(25))
For example:
from math import pi, sqrt
print(pi)
print(sqrt(25))

Answered By

5 Likes


Related Questions