What is the difference between ‘from’ and ‘import’ in Python?

In Python, both ‘from’ and ‘import’ are used to bring in modules or specific functions from a module.

The import statement is used to bring in an entire module. It allows you to access all functions within the module in your code, but you need to add the module name as a prefix when using them. For example:

import math

result = math.sqrt(25)
print(result)

The code above imports the built-in math module in Python using “import math” and calculates the square root using the “math.sqrt()” function.

The `from` statement is used to import specific functions from a module. It allows you to use these functions directly without using the module name as a prefix. For example:

from math import sqrt

result = sqrt(25)
print(result)

The above code imports the sqrt function from the math module and directly calculates the square root using the sqrt() function.

In summary, the import statement imports an entire module and requires the use of the module name as a prefix to access its functionality; whereas the from statement imports specific functions from a module and allows for direct use without the need for a module name prefix.

bannerAds