Explain Import Statement in Python
Python has many built-in functions like print(), abs(), int(), and len(). These do different things, like printing stuff or finding the length of something. But these built-in ones have their limits. To make fancier programs, we can use modules.
Python comes with lots of modules in its Standard Library. These modules give you access to system stuff or ready-made solutions. They’re always included with any Python you install.
=> When we bring in a module using Python’s “import” command, Python looks for that module first in the local area. It does this by using the “__import__()” function. Whatever this function gives back affects what the code shows as a result.
Example:
import math
pie_value = math.pi
print("The value of pi is : ", pie_value)
Output:
The value of pi is :Â 3.141592653589793
=>Â In the code we saw earlier, we imported the “math” module. We can access its stuff by thinking of it like a box full of things, and “pi” is one of those things. The “__import__()” function helps get the value of “pi”. Instead of bringing in the whole box (module), we can just get “pi”. We can also use “from” to import a file in Python.
Example:
from math import pi
pie_value = pi
print("The value of pi is : ", pie_value)
Output:
The value of pi is :Â 3.141592653589793
=>Â In the code mentioned earlier, the “math” module wasn’t brought in entirely, only the “pi” variable was imported. Using “*”, all the functions and constants from the module can be imported.
Example:
from math import *
print(pi)
print(factorial(3))
Output:
3.141592653589793
6
Conclusion:
The import function in Python allows you to bring in modules or specific elements from those modules into your code. You can import entire modules or only specific variables, functions, or constants. It helps organize and reuse code by letting you access existing functionalities or libraries, enhancing the capabilities of your programs without having to rewrite everything from scratch.