How to use modules in Python 4

1 The difference between modules, packages and libraries

In Python, the English of a module is "module", which is a file with the suffix py; the English of a package is "package", which is a directory containing multiple modules; the English of a library is "library", which contains Packages and modules for related functionality.

2 Representation of modules

In Python, a module is "package name (library name). Module name", and to use a function in a library, package or module, you need the import keyword to import the function. There are two ways to use import to import functions, one is the import format, and the other is the from...import format.

2.1 import format

The following code uses the import format to generate a random number within a specified range using the randint() function under the import module.

import random
random.randint(0,10)

Among them, when calling the randint() function under the import module, the format of "module name.function name" needs to be used. If the following code is directly written, the program will report an error.

import random
randint(0,10)

It should be noted that the import format can only be followed by the library name, package name or module name, but not the function name. The following code program reports an error, and the error message is shown in Figure 1.

Figure 1 Error message

The meaning of the error message is "Cannot find the module named 'random.randint', 'randint' is not a package name", from the error message can also be seen, the library name, package name or module name after the import.

2.2 from...import format

The following code uses the from...import format to generate a random number within the specified range using the randint() function under the import module.

from random import randint
randint(0,10)

Among them, when calling the randint() function under the import module, the function name can be used directly.

Guess you like

Origin blog.csdn.net/hou09tian/article/details/130916296