Python Imports
Hello Learner…. in this session, you can learn about import keyword and how to use this.
Python Imports
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements.
Python modules have a filename and end with the extension .py
.
Definitions inside a module can be imported to another module or the interactive interpreter in Python.
We use the import
keyword to do this.
For example, we can import the math
module by typing the following line:
1 | import math |
We can use the module in the following ways:
1 2 | import math print (math.pi) |
Output
3.141592653589793
Now all the definitions inside math
module are available in our scope.
We can also import some specific attributes and functions only, using the from
keyword.
For example:
1 2 | from math import pi print (pi) |
Output
3.141592653589793
While importing a module, Python looks at several places defined in sys.path
. It is a list of directory locations.
1 2 | import sys print (sys.path) |
Output
['C:\\Users\\Arjun', 'C:\\Users\\Arjun\\anaconda3\\python37.zip', 'C:\\Users\\Arjun\\anaconda3\\DLLs', 'C:\\Users\\Arjun\\anaconda3\\lib', 'C:\\Users\\Arjun\\anaconda3', '', 'C:\\Users\\Arjun\\anaconda3\\lib\\site-packages', 'C:\\Users\\Arjun\\anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\Arjun\\anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Arjun\\anaconda3\\lib\\site-packages\\Pythonwin', 'C:\\Users\\Arjun\\anaconda3\\lib\\site-packages\\IPython\\extensions', 'C:\\Users\\Arjun\\.ipython']
We can also add our own location to this list.
No comments:
Post a Comment