If a program is too long, it may be useful to split it into several files. If you have definied functions, it is also useful to be able to use them in several programs.
A module is a file which is defined in one file and can be reused in another file and which contains Python definitions and applications.
- Standard libraries, custom libraries and third-party libraries
- Local modules that are only available for one program
A library is included with the import statement. A standard example is the import of the Mathmodule, which provides mathematical constants and functions.
Several modules can be imported separated by a comma: Import math, random
For an overview, these are usually written at the beginning of the program.
If you want to use e.g. Pi, you have to specify the name of the function when using the constants: math.pi
Alternatively you can just import Pi and don’t have to specify the name of the module explicitly: from math import pi
If you add an as to the import command, it is possible to rename the function: import math as algebra
With the dir function you can display the names defined in a module: dir(math)
If you have written a program in which you have defined a function, for example, you can import it as a module into a new program, provided it is stored in the same file path as a Python file (.py). For this you simply use: import name