The use of modules in Python 1

1 Module overview

In Python, a module is actually a file with a suffix of py, which contains defined variables and statements. When the same variable or function needs to be used in multiple files, if the same code that defines these variables or functions is copied to each file, a lot of redundant code will be generated. At this point, the definitions of these variables or functions can be written in a module, and the module can be called at the beginning of each file.

2 Compilation of modules

In the function mode of IDLE, customize a function, the code is as follows:

def yang_func():
    print('Hello World')

The function of this function is to output "Hello World" information, and save the file as "yang_module.py", which is the created module.

3 module import

Use import at the beginning of the newly created Python file to import the module written in "2 Module writing".

import yang_module

After that, you can use the functions defined in this module, the code is as follows.

yang_module.yang_func()

Among them, yang_module is the module name, and yang_func is the function name defined in the module.

4 Precautions

When using modules, you need to pay attention to where the module files are saved. Module files can be saved in three locations (1) in the same directory as the currently executed file (2) IDLE library file path, if the default path is used when installing IDLE, the library file path is

"C:\Users\username\AppData\Local\Programs\Python\Python version\Lib(3) The installation location of IDLE, if the default path is used when installing IDLE, the installation location of IDLE is "C:\Users \Username\AppData\Local\Programs\Python\Python Version\

Guess you like

Origin blog.csdn.net/hou09tian/article/details/129915167
Recommended