Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Summarize some of the common problems with Python programmers


Jun 01, 2021 Article blog


Table of contents


The lingual error

Let's start with the basics, starting with what happened before those who had just learned to program. I f you've already made up some of your journeys, the following may seem simple. If you've ever tried teaching novices how to program, they may not be that simple.

The Python code entered in the interaction prompt

In >>> interaction prompt you can only enter Python code, not system commands. F rom time to time someone emacs LS or editing command under this prompt, which is not Python code. T here are ways to call system commands (such as os.system and os.popen) in Python code, but not as directly as directly entering commands. If you want to start a Python file in an interactive prompt, use the import file instead of the system command python file.py .

Print statements (just) are required in the file

Because the interactive interpreter automatically outputs the results of the expression, you don't need to interactively type a full print statement. This is a great feature, but remember that in code files, you usually only have to print statements to see the output.

Watch out for automatic extensions in Windows

If you edit code files in Windows using Notepad, carefully select the "All Files" (All Files) type when you keep it, and explicitly add a suffix to your .py O therwise, Notepad will add a .TXT makes it impossible to run the program in some startup methods. T o make matters worse, word processing software such as word or writing boards also adds formatting characters by default that Python syntax does not recognize. S o remember to always select All Files (all files) under Windows and save them as plain text, or use more "programmable-friendly" text editing tools, such as IDLE In IDLE remember to add the extension of .py manually when you save it.

The question of clicking the icon under the window

Under the window, you can start a Python program by clicking on Python files, but this can sometimes be problematic. F irst of all, the program's output window at the end of the program also disappeared, to let it not disappear, you can add a raw_input() call at the end of the file in addition, remember that if there is a mistake, the output window immediately disappeared to see your error message, call your program in other ways: . For example, start from the system command line, use import statements with prompts, or options in the IDLE menu, and so on.

The import is only valid for the first time

You can run it by entering a file in the interaction prompt, but only once in a session. T he next inlet is simply to return the code that the loaded module wants to force Python to reload a file, call function overload (module) to do this. Note Use parentheses for reloading, not parentheses for imports.

Blank lines (just) play a role in the interaction prompt

Blank lines and comments in the module file are ignored, but when you type code in the interaction prompt, the blank line represents the end of a compound statement In other words, the blank line tells the interaction prompt that you have completed a compound statement. Don't type Carriage Return until you're really done In fact, when you're starting a new statement, you need to type an empty line to end the current statement - the interaction prompt runs only one statement at a time.

The code is wrong

Once you start writing Python code carefully, the next bunch of pitfalls is even more dangerous: these are basic code errors with cross-language features and often bother unsuppable programmers.

Don't forget the colon

This is one of the most common mistakes novice programmers can make: don't forget to add a colon at the end of the opening statement of the compound statement (if, while, the first line of the wait statement). Y ou may have forgotten this at first, but soon it will become a subconscious habit. 75% of students in the classroom will remember this on the day.

Initialize the variable

In Python the name in an expression is not intended to work until it is assigned: it avoids some input errors, and it also avoids the default question of what type of problem it should be (0, no,", ,?). Remember to initialize the counter to 0, the list to [] and so on.

Start with the first column

Be sure to start with the top-level, unnared code in the first column on the far left. T his includes code that is not nested in the module file, as well as code that is not nested in the interaction .Python uses indentation to distinguish nested snippets of code, so a space to the left of your code means a nested block of code. In addition to indentation, spaces are usually ignored.

Indentation is consistent

Avoid mixing tabs and spaces in the same block of code unless you know how the system running your code handles labels. O therwise, what appears to be an indentation of the label in your editor Python be seen as some space insurance, all with labels in each block of code or all with spaces; How much to use is up to you.

Use parentheses when a function is called

Whether or not a function requires arguments, you must add a pair of parentheses to call it. T hat is, use a function () instead function.Python function is simply an object with special functionality (calls), which are triggered in parentheses. L ike all objects, they can also be assigned to variables and used indirectly: x = function:x( I n Python training, such errors often occur in the operation of files. Y ou'll see newbies using file.close to close a problem instead of file.close() Because it is legal to refer to a function in Python without calling it, the operation without parentheses (file.close) is silently successful, but the file is not closed!

Do not use expressions or paths when importing

Use the folder path or the extension of the file on the system's command line, but not in the import statement. T hat is, use import mod instead import mod.py or import dir / mod.py I n practice, this is probably the second most common mistake a beginner makes. B ecause the module has a suffix other than .py (for example, a pyc file), forcing a suffix to be written is not only grammatical, it makes no sense. T he format of the system-related directory path comes from the settings of your module search path, not import statement. Y ou can use points in the file name to point to the subdirectory of the package (for example, import dir1.dir2.mod), but the leftmost directory must be found through the module search path and there is no other path format in the import. The incorrect statement import mod.py is considered by Python to be a package that loads a module mod and then tries to report a series of inexplicable error messages by finding a module called a moD in a directory called MOD and finally finding nothing.

Do not write the code in Python

Here are some memo tips ç for unfamiliar Python programmers:

When testing with conditions, you do not have to enter parentheses (for example, if (X s 1) :). If you like, it's okay to add parentheses, but it's completely redundant here.

Don't end your statement with a semicolon It's technically legal in Python but it's useless unless you're putting a lot of statements on the same line (for example, X is 1). Y = 2; Z = 3)。

Do while not embed assignment statements (for example, while x - next()! = NULL))。 In Python a statement cannot appear where an expression is needed, and the assignment statement is not an expression.

Programming error

Here's finally a look at the problems you might encounter when you use more of the features in Python (data types, functions, modules, classes, and so on). D ue to space constraints, this is as streamlined as possible, especially for some advanced concepts. For more details, read the "Tips" and Gotchas of Python The 2nd Edition.

Calls to open files do not use modules to search for paths

When you call open() in Python to access an external file, the module search path is not used in Python to locate the target file. I t will use the absolute path you provided, or assume that the file is in the current working directory. The module search path is only serviced for module loading.

Different types correspond to different methods

The method of a list is that it cannot be used on strings, and vice versa. T ypically, method calls are related to data types, but internal functions are typically available on many types. For example, the list inversion method is only useful for lists, but the LEN function applies to any object with a length

Immutable data types cannot be changed directly

Remember that you can't directly change an immutable object (for example, tuples, strings):

T = (1,  2,  3)
T[2]  =  4          # 错误

Build a new object with tiles, joins, and so on, and assign the value of the original variable to it as needed because useless memory is automatically reclaimed in Python so it's not as wasteful as it seems:

T = T[:2] + (4,)  # 没问题了: T 变成了 (1, 2, 4)

Use simple loops instead of simultaneously or in scope

When you want to traverse all elements of an ordered object from left to right, it is easier to write with a simple for loop (for example, for x in seq:) than a count loop based on while- range- and usually run faster unless you need to, try to avoid using a range in a loop: . L et Python solve the labeling problem for you In the following example there are no problems with the three loop structures, but the first one is usually better; In Python simplicity is paramount.

S = "lumberjack"for c in S: print c                   # 最简单for i in range(len(S)): print S[i]    # 太多了i = 0                                 # 太多了while i < len(S): print S[i]; i += 1

Don't try to get results from functions that change objects

Direct change operations such as method list.append() and list.sort() change an object, but do not return objects that they change (they return none); The right thing to do is to call them directly instead of assigning the results often to see beginners write code like this:

mylist = mylist.append(X)

The goal is to get additional results, but in fact doing so will give MYLIST no assignment, rather than the changed list. A more special example is the idea of traversing elements in a dictionary with sorted key values, see the following example:

D = {...}
for k in D.keys().sort(): print D[k]

Almost succeeded --keys method creates a list of keys and sorts the list in some way -- but because a method returns none, the loop fails because it's actually going to go through none (which is not a sequence) to correct the code, separate the method calls, and put them in different statements, as follows:

Ks = D.keys()
Ks.sort()
for k in Ks: print D[k]

Type transformations exist only in numeric types

In Python an expression such as 123 + 3.145 works - it automatically converts the integer to a floating-point type and then uses the floating-point operation but the following code goes wrong.

S = "42"
I = 1
X = S + I        # 类型错误

It's also intentional, because it's not clear: whether to convert a string to a number (added) or a number to a string (to connect), in Python we think "clear is better than ambiguity" (i.e., EIBTI (explicitly better than implied), so you have to manually convert the type:

X = int(S) + I   # 做加法: 43
X = S + str(I)   # 字符串联接: "421"

The data structure of the loop causes the loop

Although this is rare in practice, if a collection of objects contains references to itself, this is called a circular object. If a loop is found in an object, Python outputs a [... ] to avoid getting stuck in an infinite loop:

>>> L = ['grail']  # 在 L中又引用L自身会
>>> L.append(L)    # 在对象中创造一个循环
>>> L['grail', [...]]

In addition to knowing that these three points represent loops in an object, this example is also worth learning from. Y our code may go wrong because you may inadvertently have the structure of such a loop in your code. If necessary, maintain a list or dictionary to represent objects that have already been accessed, and then check it to see if you have encountered a loop.

Assignment statements do not create a copy of the object, only a reference

This is a core idea of Python and sometimes mistakes can occur when the behavior is not right. I n the following example, a list object is assigned a variable named Large, which is then referenced in the list number. Changing the size internally also changes the objects referenced by the medium because they both point to the same object.

>>> L = [1, 2, 3]        # 共用的列表对象
>>> M = ['X', L, 'Y']    # 嵌入一个到L的引用
>>> M
['X', [1, 2, 3], 'Y']
>>> L[1] = 0             # 也改变了M
>>> M
['X', [1, 0, 3], 'Y']

Usually this is important only in slightly larger programs, and these common references are usually really what you need if not, you can explicitly create a copy for them to avoid common references; For a list, you can create a top-level copy by using a slice of an empty list:

>>> L = [1, 2, 3]
>>> M = ['X', L[:], 'Y']   # 嵌入一个L的副本
>>> L[1] = 0               # 仅仅改变了L,但是不影响M
>>> L
[1, 0, 3]
>>> M
['X', [1, 2, 3], 'Y']

The range of tiles starts from the default of 0 to the maximum length of the sequence being sliced. I f both are omitted, the slice extracts all the elements in the sequence and creates a top-level copy (a new, non-public object). For dictionaries, use the dictionary's dict.copy() method.

Statically identifies the variable name of the local domain

Python default treats variable names assigned to a function as native, they exist in the scope of the function, and only exist when the function is running. T echnically, the python is recognized statically when compiling DEF code, rather than when the runtime encounters assignments. I f you don't understand this, it will lead to misunderstanding. For example, look at the following example, what happens when you assign a variable after a reference:

>>> X = 99
>>> def func():
...     print X      # 这个时候还不存在
          ... 
        >>> func( )          # 出错了!

You get an "undefined variable name" error, but the reasons are subtle. W hen compiling this code, the statement assigned to X in Python is considered to be considered anywhere in the function. A local variable name but then when the function is actually run and the print statement is executed, the assignment statement does not yet occur, so Python reports an "undefined variable name" error.

In fact, what you want to do in the previous example is very vague: do you want to output that global X first, and then create a local X, or is this a program error If you really want to output this global X, you need to declare it in a global statement, or reference it by the name of the envelope module.

Default parameters and variable objects

When you execute a DEF statement, the value of the default argument is resolved and saved only once, not each time the function is called. T his is usually what you want, but because the default values need to remain the same object every time you call, you should be careful when you try to change the mutable defaults. For example, the following function uses an empty list as the default, and then changes its value each time a function is called later:

>>> def saver(x=[]):   # 保存一个列表对象
...     x.append(1)    # 并每次调用的时候
...     print x        # 改变它的值
...
>>> saver([2])         # 未使用默认值
[2, 1]
>>> saver()            # 使用默认值
[1]
>>> saver()            # 每次调用都会增加!
[1, 1]
>>> saver()
[1, 1, 1]

Some people see this as a feature of Python - because variable default parameters maintain their state every time a function calls, they provide something similar to static local function variables in the language, but it's strange when you first come across it, and there's an easier way to save state (such as a class) between different calls in Python

To get rid of this behavior, create a copy of the default argument with a slice or method where the function begins, or move the expression of the default value into the function; As long as these values are in the function each time the function is called, a new object is given each time:

>>> def saver(x=None):
  ...     if x is None: x = []   # 没有传入参数?
    ...     x.append(1)            # 改变新的列表
      ...     print x
        ...
          >>> saver([2])                 # 没有使用默认值
        [2, 1]
>>> saver()                    # 这次不会变了
        [1
        ]>>> saver()[1]

Other common programming traps

Here are some of the other pitfalls that you can't elaborate on here:

The order of statements in the top-level file is careful: because running or loading a file runs its statements from top to bottom, be sure to place calls to functions or classes that you don't nest behind the definition of a function or class.

Reloading does not affect the name used from the load: Reloading is best used with import statements If you are using a statement, remember to re-run it from after reloading, otherwise you still use the old name before.

The order of mixing in multiple inheritances is refined: this is because the search for superclasses is left-to-right, at the head of a class definition, and if duplicate names appear in multiple superclasses, the class name on the far left is quasi.

Empty in the try statement, except that the clause may catch more errors than you expect. Empty in the attempt statement, except that the clause indicates that all errors are caught, even true program sys.exit() are caught.

These are W3Cschool编程狮 about summing up some of the common problems of Python programmers, I hope to help you.