Python Programming - Import

Python Programming – Import

It is a good practice to break large programs into modules, which makes it easy for the programmer to understand each module separately rather than the whole program at once. A module is a file that contains definitions and statements of Python functions. Python modules have a filename that terminates with the extension .py.

Alike, C, C++, and Java, the definitions inside a module can be imported to another module or the interactive interpreter in Python, where header files and namespaces are used in C/C++/Java. We use the import keyword in Python to achieve this. For example, we can import the math module by typing in import math as shown in Code 2.31.

Code: 2.31.

>>> import math

Now all the definitions inside the math module are available for our use. We can also import some specific attributes and functions only, using the form of a keyword, see Code 2.32for example.

Code: 2.32.

>>> from math import pi
>>> pi

While importing a module. Python looks at several places defined in sys. path for importing all the methods in that module as shown in Code: 2.33., the output for the same is shown in Fig. 2.3., which represents a list of directories.

Code: 2.33.

>>> import sys

Python Programming - Import chapter 2 img 1

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *