Python errors, exceptions, and modules

Posted by stopblackholes on Wed, 05 Jan 2022 01:17:20 +0100

This article mainly talks about two aspects, errors and exceptions, and modules. It is inevitable to encounter error messages during programming. There are many kinds of error messages in Python. The two common types are syntax errors and logic errors. There are many types of logic errors, which occupy most of the exceptions. Let's start to introduce the relevant knowledge of these two concepts.

Errors and exceptions

syntax error

Syntax error is expressed in English as syntax error, followed by some explanation information about the error, which is convenient for you to find the bug in the statement, as follows:

In [5]: print('naitangmao)
  File "<ipython-input-5-d5b793a8884b>", line 1
SyntaxError: EOL while scanning string literal

Syntax error, as the name suggests, is that your code statement is written incorrectly. For example, the error of the above statement is that a quotation mark is missing. After an error occurs, the interpreter will give the name of the file and the error line number, and there is a "^" below the error line. This prompts you that the location of the code error is usually in front of the arrow. These prompts will facilitate the writer to find the error as soon as possible.


Sometimes a line of code may have no syntax errors, but the interpreter will also report red when executing. This error message can be called exception. Compared with syntax errors, there are more types and more common exceptions.

Two simple examples:

In [6]: print(1/0)
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-6-2fc232d1511a> in <module>
----> 1 print(1/0)

ZeroDivisionError: division by zero

We all know that 0 cannot appear as a denominator, so Python will give a zero division error and remind you that it is a zero division error.

In [9]: 1+'1'
TypeError                                 Traceback (most recent call last)
<ipython-input-9-d3bd1e37a107> in <module>
----> 1 1+'1'

TypeError: unsupported operand type(s) for +: 'int' and 'str'

There is no addition operation between the integer and the string. After analysis, the interpreter will give a TypeError, which is a type error, and the error explanation will be given later.

exception handling

For the Python interpreter, if an exception occurs in a certain part of a program, the code behind it will not be run, but there are methods in Python to handle the exception so that the exception does not report red, so as to help the whole program run. This behavior is called catching exceptions to try Except statement combination implementation.

In [11]: a = 1;b = '2'
In [12]: try:
    ...:     print(a+b)
    ...: except TypeError:
    ...:     print('Wrong type!')
Wrong type!

Process of catching exception implementation:

  • 1. Execute the part between try and except keywords
  • 2. If no exception occurs, the exception clause is ignored after the try statement is executed.
  • 3. If an exception occurs during the execution of the try clause, the rest of the clause will be ignored. If the exception matches the exception type specified after the exception keyword, the corresponding exception clause is executed. Then continue to execute the code after the try/except statement.
  • 4. If an exception occurs and there is no matching branch in the except clause, it will be passed to the previous try statement. If the corresponding processing statement is still not found, it will become an unhandled exception, terminate the program and display a prompt.

In order to avoid the occurrence of condition 4, the parent Exception of all exceptions can be used in the Exception statement, which includes all possible exceptions:

In [15]: try:
    ...:     print(a+b)
    ...: except Exception as e:
    ...:     print(e)
unsupported operand type(s) for +: 'int' and 'str'

Throw exception

raise statements can be used to actively throw an Exception, but the Exception thrown must be an Exception class or an Exception example to inherit from Exception.

In [16]: raise NameError('naitangmao')
NameError                                 Traceback (most recent call last)
<ipython-input-16-b751158801b2> in <module>
----> 1 raise NameError('naitangmao')

NameError: naitangmao

In addition to the above description, users can also define exceptions according to their own needs without too much introduction. It is recommended to master the causes of each exception and the methods of exception handling.


The second part is the module. Sometimes we may use the same function between different files. A stupid way is to copy. Python provides a mechanism to import the contents of one file into another file. Such a file can be called a module. It should be noted that not any file can be used as a module, It must be a file that contains Python definitions and declarations.

Take a simple example to help understand the above paragraph. First, you can create an file, and there is only one function in this file to filter out even numbers in a range:

In [18]: def odd(n):
    ...:     result = []
    ...:     for i in range(n):
    ...:         if i % 2 != 0:
    ...:             result.append(i)
    ...:     return result

Then we can import this module into another file. If we want to use this function, we can use the module name The method of the function name calls the function as follows:

In [20]: import odd_num
In [21]: odd_num.odd(20)
Out[21]: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

If you only want to use a sub module in a module, you can specify the part to be imported when importing, so that the sub module can be used alone without using the module name Form of function name:

In [22]: from odd_num import odd
In [23]: odd(20)
Out[23]: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

If you still want to be lazy, you can import it in the form of '*', which is to import all sub modules in a module:

In [24]: from odd_num import *

This method is often not recommended because it will make the code less readable.

If you have many customized modules, you can store these modules in a "package" for more standardization and easy to find. It should be noted that there should be a module named init Py file, which can be empty but must exist, and then the way to import modules in the package is the package name Module name.

Python also has its own module library. Some modules are built into the interpreter, and then users can directly access the interfaces of such modules, which greatly improves the efficiency, such as time, sys, etc. If you are unfamiliar with a module, you can use the dir() function to search for the definition of a module, and the returned result is a list, including the methods in the module, the interfaces available for calling, and so on.

In [24]:dir(time)
Out[24]:['_STRUCT_TM_ITEMS', '__doc__', '__loader__','__name__','__package__','__spec__','altzone','asctime','ctime','daylight',

To sum up, it is a summary of common knowledge about errors, exceptions and modules. If you are interested in higher-level use, you can find the official Python documentation, which will be introduced in more detail.

Topics: Python