Analysis of 17 common Python errors

Time:2020-9-19

For the new python, running the code in the learning process will more or less encounter some errors, which may seem more difficult at the beginning. With the accumulation of code, practice makes perfect. When encountering some runtime errors, it can quickly locate the original problem. Here are 17 common mistakes, hoping to help you


1、

Forget to add at the end of if, for, def, elif, else, class, etc:

This will result in “syntax error: invalid syntax” as follows:

if spam == 42  print('Hello!')

 

2、

Use = instead of==

It also causes “syntax error: invalid syntax”

=Is the assignment operator and = = is the equal comparison operation. The error occurs in the following code:

if spam = 42:  print('Hello!')

 

3、

Wrong use of indent

“Indentation error: unexpected indent,” “indentation error: unindent does not match any outer indentation level,” and “indentation error: expected an indented block”

Remember that indent increases are only used after statements that end with: and must be restored to the previous indent format. The error occurs in the following code:

print('Hello!')  print('Howdy!')

 

Or:

if spam == 42:  print('Hello!')print('Howdy!')

 

4、

Forget to call len() in a for loop statement

Causes “typeerror: ‘list’ object cannot be interpreted as an integer”

Usually you want to iterate over a list or string element by index, which requires calling the range() function. Remember to return the len value instead of the list.

The error occurs in the following code:

spam = ['cat', 'dog', 'mouse']for i in range(spam):  print(spam[i])

 

5、

Try to modify the value of string

Results in “typeerror: ‘STR’ object does not support item assignment”

String is an immutable data type. The error occurs in the following code:

spam = 'I have a pet cat.'spam[13] = 'r'print(spam)

 

The correct way is to:

spam = 'I have a pet cat.'spam = spam[:13] + 'r' + spam[14:]print(spam)
6、

Attempt to connect a non string value to a string

Causes “typeerror: can’t convert ‘Int’ object to STR implicitly”

The error occurs in the following code:

numEggs = 12print('I have ' + numEggs + ' eggs.')

The correct way is to:

numEggs = 12print('I have ' + str(numEggs) + ' eggs.')numEggs = 12print('I have %s eggs.' % (numEggs))

 

7、

Forget to put quotation marks at the beginning and end of the string

Causes “syntax error: EOL while scanning string literal”

The error occurs in the following code:

print(Hello!')print('Hello!)myName = 'Al'print('My name is ' + myName + . How are you?')

 

8、

Misspelled variable or function name

“NameError: name ‘fooba’ is not defined”

The error occurs in the following code:

foobar = 'Al'print('My name is ' + fooba)spam = ruond(4.2)spam = Round(4.2)

 

9、

Misspelled method name

“Attributeerror: ‘STR’ object has no attribute ‘lowerr'”

The error occurs in the following code:

spam = 'THIS IS IN LOWERCASE.'spam = spam.lowerr()

 

10、

The reference exceeds the list maximum index

Results in “indexerror: list index out of range”

The error occurs in the following code:

spam = ['cat', 'dog', 'mouse']print(spam[6])

 

11、

Use nonexistent dictionary key value

“Keyerror ‘spam'”

The error occurs in the following code:

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}print('The name of my pet zebra is ' + spam['zebra'])

 

12、

Try using the python keyword as the variable name

Causes “syntax error: invalid syntax”

Python key cannot be used as variable name. The error occurs in the following code:

class = 'algebra'

 

The keywords of Python 3 are: and, as, assert, break, class, continue, def, del, elif, else, except, false, finally, for, from, global, if, import, in, is, lambda, none, non local, not, or, pass, raise, return, true, try, while, with, yield

 

13、

Use the increment operator in a new variable definition

“NameError: name ‘foobar’ is not defined”

Do not use 0 or an empty string as the initial value when declaring a variable. The phrase “spam + = 1” of the auto increment operator is equal to spam = spam + 1, which means that the spam needs to specify a valid initial value.

The error occurs in the following code:

spam = 0spam += 42eggs += 42

 

14、

Use local variables in functions before defining local variables (there are global variables with the same name as local variables)

“Unboundlocalerror: local variable ‘foobar’ referenced before assignment”

It is very complicated to use a local variable in a function and there is a global variable with the same name. The use rule is: if anything is defined in a function, if it is only used in a function, it is local, otherwise it is a global variable.

This means that you can’t use it as a global variable in a function before you define it.

The error occurs in the following code:

someVar = 42def myFunction():  print(someVar)  someVar = 100myFunction()

 

15、

 

Try to create an integer list using range()

Results in “typeerror: ‘range’ object does not support item assignment”

Sometimes you want an ordered list of integers, so range () seems like a good way to generate it. However, you need to remember that range() returns “range object”, not the actual list value.

The error occurs in the following code:

spam = range(10)spam[4] = -1

Correct writing method:

spam = list(range(10))spam[4] = -1

(Note: in Python 2, spam = range (10) works, because in Python 2 range() returns a list value, but in Python 3, the above error occurs.)

 

16、

There is no + + or — increment and decrement operator.

Causes’ syntax error: invalid syntax ‘

If you’re used to other languages like C + +, Java, PHP, etc., you may want to try + + or — increment and subtract a variable. There is no such operator in Python.

The error occurs in the following code:

spam = 1spam++

Correct writing method:

spam = 1spam += 1

 

17、

Forget to add a self parameter to the first parameter of the method

“Typeerror: mymethod() takes no arguments (1 given)”

The error occurs in the following code:

class Foo():  def myMethod():      print('Hello!')a = Foo()a.myMethod()