2
头图

For a Pythoner who is just getting started, running the code during the learning process will more or less encounter some errors, which may seem more strenuous at first. As the amount of code accumulates, practice makes perfect. When you encounter some runtime errors, you can quickly locate the original problem. Here are 17 common mistakes that I hope can help you.

1、
Forgetting to add: at the end of if, for, def, elif, else, class, etc. declarations will cause " SyntaxError: invalid syntax " as follows:

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

2、
Use = instead of ==
It will also cause " SyntaxError: invalid syntax "= is an assignment operator and == is an equal comparison operation. The error occurs in the following code:

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

3、
Incorrect use Indent lead to " IndentationError: Unexpected indent ", " IndentationError: the Unindent does not match the any Outer indetation Level " and " IndentationError: expected AN indented Block " Remember shrink Increment is only used after the sentence that ends with:, and then must be restored to the previous indentation format. The error occurs in the following code:

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

or:

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

4、
Forgot to call len() in the for loop

Causes " TypeError:'list' object cannot be interpreted as an integer "

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

The error occurs in the following code:

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

5, attempts to modify the value of string, resulting 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 approach is:

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

6, trying to concatenate a non-string value with a string results in " TypeError: Can't convert'int' object to str implicitly " This error occurs in the following code:

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

The correct approach is:

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

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

7, forgets to add quotation marks at the beginning and end of the string, resulting in " SyntaxError: EOL while scanning string literal " This error occurs in the following code:

print(Hello!')

print('Hello!)

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

8、
The spelling of the variable or function name causes " NameError: name'fooba' is not defined ". This error occurs in the following code:

foobar = 'Al'
print('My name is ' + fooba)

spam = ruond(4.2)

spam = Round(4.2)

9, method name spelling error leads to " AttributeError:'str' object has no attribute'lowerr' " This error occurs in the following code:

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

10、
Quoting exceeding the maximum index of the list results in " IndexError: list index out of range " This error occurs in the following code:

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

11, using a non-existent dictionary key value results in " KeyError:'spam' " This error occurs in the following code:

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

12, Trying to use Python keywords as variable names results in " SyntaxError: invalid syntax " Python keys cannot be used as variable names. This error occurs in the following code:

class = 'algebra'

The keywords of Python3 are: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13、
Use value-added operators in a definition of a new variable

Causes " NameError: name'foobar' is not defined "

Do not use 0 or an empty string as the initial value when declaring a variable. In this way, a sentence of spam += 1 that uses the increment operator is equal to spam = spam + 1, which means that spam needs to specify a valid initial value.

The error occurs in the following code:

spam = 0
spam += 42
eggs += 42

14. uses local variables in the function before defining local variables (there is a global variable with the same name as the local variable at this time) resulting in " UnboundLocalError: local variable'foobar' referenced before assignment " When there is a global variable with the same name at the same time, it is very complicated. The usage rule is: if anything is defined in the function, if it is only used in the function, it is local, otherwise it is a global variable. This means that you cannot use it as a global variable in a function before defining it. The error occurs in the following code:

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

15, Trying to use range() to create a list of integers results in " TypeError:'range' object does not support item assignment " Sometimes you want to get an ordered list of integers, so range() seems to generate this list Great way. However, you need to remember that range() returns a "range object", not the actual list value. The error occurs in the following code:

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

Correct writing:

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

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

16, does not exist ++ or - increment and decrement operators. Causes " SyntaxError: invalid syntax ". If you are used to other languages such as C++, Java, PHP, etc., you may want to try using ++ or --- increment and decrement a variable. There is no such operator in Python. The error occurs in the following code:

spam = 1
spam++

Correct writing:

spam = 1
spam += 1

17, forgetting to add the self parameter to the first parameter of the method leads to " TypeError: myMethod() takes no arguments (1 given) " This error occurs in the following code:

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

用户bPcWok5
24 声望4 粉丝