[100 days proficient in python] Day15: python third-party modules and packages, how to execute the module in the form of the main program

Table of contents

1 Commonly used third-party modules

2. Installation and use of third-party modules

2.1 Install third-party modules:

2.2 Import third-party modules:

2.3 Using third-party modules:

 3 The module is executed in the form of the main program

 4 Packages in python

 4.1 Package structure of python program 

4.2 Create package 

4.3 Import and use of packages in python

5 Differences between third-party modules and packages

6 Actual combat, simulated calculation of personal income tax


        The existence of third-party modules and packages enriches Python's functionality and ecosystem, making Python a powerful and flexible programming language. You can install and use third-party modules and packages suitable for your project as needed, thereby improving development efficiency and function expansion.

      Third-party modules are Python code libraries written by other developers or organizations to provide additional functions and tools to enrich the Python ecosystem. Before using third-party modules, they need to be installed first.

1 Commonly used third-party modules

        The following are some commonly used third-party modules, which provide a variety of functions, covering network requests, data processing, image processing, scientific computing, database connection, web development, etc.:

  1. requests: Used to send HTTP requests, perform network communication and obtain data.
  2. numpy: Provides high-performance numerical computing functions for array and matrix operations.
  3. pandas: for data processing and analysis, providing data structures and functions, such as DataFrame and Series.
  4. matplotlib: Used to draw various types of charts and graphs.
  5. seaborn: A statistical data visualization library built on top of matplotlib for prettier and simpler charting.
  6. scikit-learn: A library for machine learning and data mining that provides various algorithms and tools.
  7. TensorFlow and PyTorch: Libraries for deep learning and neural networks that provide powerful functions for building and training models.
  8. OpenCV: A computer vision library for image and video processing.
  9. BeautifulSoup: for parsing HTML and XML documents, for web scraping and data extraction.
  10. Flask and Django: A framework for web development that simplifies the process of building websites and web applications.
  11. SQLAlchemy: A library for database connection and manipulation, providing object-oriented database mapping.
  12. Pillow: A library for image processing and image format conversion.
  13. Pygame: A library for creating games and interactive applications.

        The above are just a small number of commonly used third-party modules. Python's ecosystem is very rich, and there are many other powerful and widely used third-party modules to choose from. You can choose suitable third-party modules according to your project requirements to improve development efficiency and function expansion.

2. Installation and use of third-party modules

Let's take requestsmodules as an example to explain in detail the usage examples of third-party modules:

2.1 Install third-party modules:

First, we need to use the package management tool pip to install requeststhe module. Execute the following commands on the command line:

pip install requests

2.2 Import third-party modules:

After the installation is successful, import the module in the Python script requests:

import requests

2.3 Using third-party modules:

requestsModules are an excellent tool for making HTTP requests to web servers. Here are some common example usages:

  • Send a GET request:
  • import requests
    
    url = 'https://api.github.com'
    response = requests.get(url)
    
    if response.status_code == 200:
        print('Request successful')
    else:
        print('Request failed')
    

    Send a POST request:

  • import requests
    
    url = 'https://httpbin.org/post'
    data = {'key1': 'value1', 'key2': 'value2'}
    response = requests.post(url, data=data)
    
    print(response.text)
    

    download file:

  • import requests
    
    url = 'https://example.com/image.jpg'
    response = requests.get(url)
    
    if response.status_code == 200:
        with open('image.jpg', 'wb') as f:
            f.write(response.content)
        print('Download successful')
    else:
        print('Download failed')
    

    These examples are just requeststhe tip of the iceberg of what the module can do. There are many excellent third-party modules in the Python community, covering a variety of different fields and functions, to meet various needs. You can find and install third-party modules that suit your project's needs by searching the Python Package Index (PyPI) or using pip.

 3 The module is executed in the form of the main program

        When a module is executed as the main program, Python sets its __name__special variable to __main__, which allows us to distinguish whether the module is imported or executed as the main program. In the main program, we can write some code to test the function of the module or perform specific tasks.

The following is a sample code showing how to execute the module as the main program:

# 示例模块 my_module.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def main():
    print("This is the main program of my_module.py")
    result = add(5, 3)
    print("Result of add function:", result)

    result = subtract(10, 4)
    print("Result of subtract function:", result)

if __name__ == "__main__":
    main()

In the above example, we created a my_module.pymodule named . addThe sum function is defined in the module subtractand mainboth functions are tested in the function. In the last line of code if __name__ == "__main__":, we check __name__if it is __main__, and if so, call mainthe function, so that the module will be executed as the main program.

When we run this my_module.pymodule, the output is as follows:

This is the main program of my_module.py
Result of add function: 8
Result of subtract function: 6

If we import it elsewhere my_module.py, then mainthe function will not be called, only the functions and variables in the module will be imported and available elsewhere. This design can make the module more reusable.

 4 Packages in python

         The package structure in a Python program is a hierarchical structure for organizing and managing code. The package structure consists of packages (Package) and modules (Module).

  1. Package: A package is a folder containing modules and subpackages. It is used to organize related modules together to form a namespace and avoid module name conflicts. A package is a __init__.pydirectory containing special files . This file is used to identify the directory as a package. Packages can have multiple levels of subpackages, forming a filesystem-like folder structure.

  2. Module: A module is a file that contains Python code. A module can contain code such as functions, classes, variables, etc., which can be imported and used by other modules or packages. Module filenames usually .pyend in .

my_package/
    __init__.py
    module1.py
    module2.py
    ...
  • my_packageis the name of the package and is a folder containing multiple modules.
  • __init__.pyis an empty file that identifies my_packagethe directory as a package. If this file does not exist, Python will not my_packagetreat the directory as a package.
  • module1.py, module2.pyetc. are module files that contain specific functions.

Using packages can better organize code, avoid module name conflicts, and improve code maintainability.

 4.1 Package structure of python program 

        The package structure can make the project more structured and easier to maintain, while avoiding module name conflicts . The package structure in the Python program can be flexibly designed according to the needs of the project to meet different development needs.

Package structure in a python project 

For example, a typical package structure could look like this:

my_project/
    main.py
    my_package/
        __init__.py
        module1.py
        module2.py
        sub_package1/
            __init__.py
            sub_module1.py
        sub_package2/
            __init__.py
            sub_module2.py

In the above example, my_projectit is the root directory of the project, which contains a main program main.pyand a my_packagepackage named . my_packageThe package contains two modules module1.pyand module2.py, and two subpackages sub_package1and sub_package2. The subpackage contains sub_module1.pyand sub_module2.pytwo modules respectively.

Through this package structure, related codes can be organized together, making the project clearer and easier to manage.

4.2 Create package 

The steps to create a package are as follows:

  1. Create a folder as the root directory of the package. The root directory of a package should contain a special file __init__.pythat tells Python to recognize the folder as a package.

  2. In the root directory of the package, create the module files you want, e.g. module1.py, module2.pyetc. These module files will contain your code.

  3. Define your functions, classes, variables, etc. in the module file.

  4. If necessary, subfolders can be created under the root directory of the package to organize related module files.

  5. In other Python scripts, use importstatements to import your packages and modules and use the functions and classes within them.

For example, suppose we want to create a my_packagepackage called , which contains two modules module1and module2, and then use the package in another script, the specific steps are as follows: 

  1. Create a folder, name it my_package, and create an empty file in that folder __init__.py.

  2. Create two module files under my_packagethe folder: module1.pyand module2.py.

 Define some functions or classes in these files, for example:

module1.py:

def greet(name):
    return f"Hello, {name}!"

module2.py:

def add(a, b):
    return a + b

Now, we can import and use this package in other Python scripts. Use the following code in your script:

from my_package import module1, module2

print(module1.greet("Alice"))
print(module2.add(3, 5))

This successfully creates a package and uses its modules in other scripts.

4.3 Import and use of packages in python

(1) In other modules, you can use importthe statement to import the modules in the package , for example:

import my_package.module1
import my_package.sub_package1.sub_module1

(2) Or use from ... import ...the statement to import specific functions or variables in the module:

from my_package import module1
from my_package.sub_package1 import sub_module1
from my_package import module1
module1.some_function()

(3)  If you want to import multiple modules at once, you can use from ... import ...the statement:

from my_package import module1, module2

(4) Use askeywords to assign aliases to modules: 

import my_package.module1 as mod1
mod1.some_function()

(5) Use fromthe statement to import the module in the package, and assign an alias to the module: 

from my_package import module1 as mod1
mod1.some_function()

my_packageNote: The files in the directory will also be executed when the package is imported __init__.py, which can be used to perform some initialization operations when importing. 

When writing your own package, you need to add a file in the package directory __init__.py. This file can be empty or contain some initialization code. This way, Python will treat this directory as a package, not just a normal folder.

Summary: A package is a mechanism for organizing and managing related modules. It can contain multi-level subpackages, and the modules in the package can be imported using importand statements.from ... import

5 Differences between third-party modules and packages

Third-party modules and packages are external tools that extend the functionality of Python, but they have some differences:

  1. Module:

    • A module is a file containing Python code, usually .pywith the suffix .
    • Modules can contain code such as functions, classes, variables, etc., and can be imported and used by other Python programs.
    • The Python standard library contains many built-in modules, such as math, randometc.
    • Third-party modules are written by other developers, do not belong to the Python standard library, and need to pipbe installed through tools such as Python.
  2. Package (Package):

    • A package is a directory containing multiple modules that must contain a __init__.pyfile named .
    • A package's directory structure can be multi-level nested to organize related modules and subpackages.
    • Packages provide a better way to organize and manage modules, help avoid module name conflicts, and provide more complex functionality encapsulation.
    • Third-party packages are usually provided as packages, such as requestspackages.

        In general, a module is a single file, while a package is a directory that contains multiple related modules. Third-party modules are usually provided as packages, but can also be individual modules. Whether it is a module or a package, they can provide additional functions and tools for Python programs, making development more convenient and efficient.

6 Actual combat, simulated calculation of personal income tax

Write a program to calculate personal income tax, and keep track of how much personal income tax you need to pay for your salary

calculate_income_tax.py 

def calculate_income_tax(income):
    # 根据个人所得税计算规则计算税额
    if income <= 36000:
        tax = income * 0.03
    elif 36000 < income <= 144000:
        tax = (income - 36000) * 0.1 - 2520
    elif 144000 < income <= 300000:
        tax = (income - 144000) * 0.2 - 16920
    elif 300000 < income <= 420000:
        tax = (income - 300000) * 0.25 - 31920
    elif 420000 < income <= 660000:
        tax = (income - 420000) * 0.3 - 52920
    elif 660000 < income <= 960000:
        tax = (income - 660000) * 0.35 - 85920
    else:
        tax = (income - 960000) * 0.45 - 181920
    return tax

def main():
    try:
        income = float(input("请输入您的工资收入:"))
        if income < 0:
            print("工资收入不能为负数!")
        else:
            tax = calculate_income_tax(income)
            print("您需要缴纳的个人所得税为:", tax)
    except ValueError:
        print("请输入有效的数字!")

if __name__ == "__main__":
    main()

The result of the operation is as follows:

 Using this program, you can enter your wages and then calculate how much personal income tax you need to pay. Note that this sample program is just a simple example, the actual personal income tax calculation may have more complicated rules, please refer to the tax laws and regulations in your region for details.

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/131927758