This article focuses on two areas: errors and exceptions and modules. There are many types of error messages in Python. The two most common types of error messages are syntax errors and logic errors. There are many types of logic errors, which make up the majority of exceptions.

Errors and exceptions

Grammar mistakes

SyntaxError: SyntaxError: SyntaxError: SyntaxError: SyntaxError: SyntaxError: SyntaxError: SyntaxError

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

Syntax errors, as the name implies, are errors in your code statements, such as this one where a quote is missing. When an error occurs, the interpreter will give you the name of the file and the error line number, and there will be a “^” under the error line. This will indicate where the code went wrong, usually in front of the arrow. This will help the writer to find the error quickly.

abnormal

Sometimes a line of code may have no syntax error, but when executed the interpreter will return a red message. This error message can be called an exception, and exceptions are more diverse and common than syntax errors.

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 zeroCopy the code

You know you can’t use 0 as a denominator, so Python will give you a ZeroDivisionError and remind you that this is a ZeroDivisionError.

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'
Copy the code

There is no addition between an integer and a string, and the interpreter will parse it and give a TypeError, which is a TypeError and will explain the error later.

Exception handling

For the Python interpreter, if an exception occurs in one part of a program, the code that follows will not be run. However, there are methods in Python that handle the exception so that the exception does not report red, thus helping the program to complete. Except statement combination implementation.

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

The process of catching an exception implementation:

  • 1. Execute the part between the try and except keywords
  • 2. If no exception occurs, the except 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 is ignored. If the exception matches the exception type specified after the except keyword, the corresponding EXCEPT clause is executed. Then proceed to the code after the try/except statement.
  • 4. If an exception occurs and there is no matching branch in the except clause, it is passed to the next level of the try statement. If no processing statement is found, it becomes an unhandled exception, terminates the program, and displays a message.

To avoid the fourth case, an except statement can use the Exception parent of all exceptions, which covers all possible exceptions:

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

An exception is thrown

The raise statement can be used to actively raise an Exception, but the Exception must be an Exception class or Exception example that inherits 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
Copy the code

In addition, you can also define exceptions based on your own requirements. You are advised to understand the causes of each exception and how to handle exceptions.

The module

The second part is modules. We might sometimes use the same function from one file to another. The clumsy way is to copy and copy. Python provides a mechanism for importing content from one file into another. It is important to note that not just any file can be considered a module, but must contain Python definitions and declarations.

An odd_num. Py file can be created with a single function that filters out even numbers in a range: odd_num.

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

We can then import the module in another file, using the module name if we want to use the function. The method with 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]
Copy the code

If you want to use only one of the submodules in a module, you can specify the parts you want to import at import time, so that the module can be used separately from the module name. The form of the 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]
Copy the code

If you want to be lazy, you can use the ‘*’ form to import all submodules in a module:

In [24]: from odd_num import *
Copy the code

This approach is often not recommended because it makes the code less readable.

If you have a lot of custom modules, you can store them in a “package” to make them more formal and easy to find. For example, the package should have a file named __init__.py, which can be empty but must exist, and then import the modules in the package by the package name. The module name.

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

In [24]:dir(time) Out[24]:['_STRUCT_TM_ITEMS', '__doc__', '__loader__','__name__','__package__','__spec__','altzone','asctime','ctime','daylight', 'get_clock_info','gmtime','localtime','mktime','monotonic','monotonic_ns','perf_counter','perf_counter_ns','process_time ', 'process_time_ns','sleep','strftime','strptime','struct_time','thread_time','thread_time_ns','time','time_ns','timezone' ,'tzname']Copy the code

This is a general overview of both errors and exceptions, and modules in general. If you’re interested in more advanced use, check the Official Python documentation for more details.