For the newcomer Pythoner In the process of learning to run the code is more or less will encounter some errors , It may seem like a lot of work at first . As the amount of code accumulates , Practice makes perfect when encountering some runtime errors, it can quickly locate the original problem . Here are some common 17 A mistake , I hope I can help you .
1、
Forget in if,for,def,elif,else,class Wait until the end of the statement : It can lead to “SyntaxError :invalid syntax” as follows :
if spam == 42 print('Hello!')
2、
Use = instead of ==
It can also lead to “SyntaxError: invalid syntax”= It's an assignment operator and == It's a comparison operation . This error occurs in the following code :
if spam = 42: print('Hello!')
3、
Incorrect use of indents leads to “IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level” as well as “IndentationError:expected an indented block” Remember that indent increase is only used to : After the closing statement , And then you have to go back to the previous indent format . This error occurs in the following code :
print('Hello!') print('Howdy!')
perhaps :
if spam == 42: print('Hello!') print('Howdy!')
4、
stay for Forget to call... In the loop statement len()
Lead to “TypeError: 'list' object cannot be interpreted as an integer”
Usually you want to iterate through an index list perhaps string The elements of , This requires calling range() function . Remember to go back to len Value instead of returning this list .
This error occurs in the following code :
spam = ['cat', 'dog', 'mouse'] for i in range(spam): print(spam[i])
5、 Try to modify string The value of “TypeError: 'str' object does not support item assignment”string It's an immutable data type , This error occurs in the following code :
spam = 'I have a pet cat.' spam[13] = 'r' print(spam)
And the right thing to do is :
spam = 'I have a pet cat.' spam = spam[:13] + 'r' + spam[14:] print(spam)
6、 Trying to connect a non string value to 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.')
And the right thing to do is :
numEggs = 12 print('I have ' + str(numEggs) + ' eggs.') numEggs = 12 print('I have %s eggs.' % (numEggs))
7、 Forgetting to put quotation marks at the beginning and end of a string leads to “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、
Misspelling variable or function names leads to “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、 A misspelled method name results in “AttributeError: 'str' object has no attribute 'lowerr' ” This error occurs in the following code :
spam = 'THIS IS IN LOWERCASE.' spam = spam.lowerr()
10、
Reference exceeds list Maximum index results in “IndexError: list index out of range” This error occurs in the following code :
spam = ['cat', 'dog', 'mouse'] print(spam[6])
11、 Using non-existent dictionary key values 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、 Try to use Python Keyword as variable name leads to “SyntaxError:invalid syntax”Python Key cannot be used as variable name , This error occurs in the following code :
class = 'algebra'
Python3 The key words 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 the value-added operator... In a new variable definition
Lead to “NameError: name 'foobar' is not defined”
Do not use... When declaring variables 0 Or an empty string as the initial value , In this way, we use a sentence of the autoincrement operator spam += 1 be equal to spam = spam + 1, It means spam You need to specify a valid initial value .
This error occurs in the following code :
spam = 0 spam += 42 eggs += 42
14、 Use local variables in functions before defining local variables ( At this time, there is a global variable with the same name as the local variable ) Lead to “UnboundLocalError: local variable 'foobar' referenced before assignment” It's very complicated to use local variables in a function and have a global variable with the same name at the same time , The rule of use is : If anything is defined in a function , If it's only used in functions, then it's local , On the contrary, it's a global variable . This means that you can't use it as a global variable in a function before defining it . This error occurs in the following code :
someVar = 42 def myFunction(): print(someVar) someVar = 100 myFunction()
15、 Try to use range() Creating a list of integers results in “TypeError: 'range' object does not support item assignment” Sometimes you want to get an ordered list of integers , therefore range() Looks like a good way to generate this list . However , You need to remember range() The return is “range object”, Not the actual list value . This error occurs in the following code :
spam = range(10) spam[4] = -1
Write it correctly :
spam = list(range(10)) spam[4] = -1
( Be careful : stay Python 2 in spam = range(10) It can be done , Because in Python 2 in range() The return is list value , But in Python 3 The above mistakes will occur in )
16、 non-existent ++ perhaps -- Self - increment and self - decrement operators . Lead to “SyntaxError: invalid syntax” If you are used to, for example C++ , Java , PHP Wait for other languages , Maybe you want to try to use ++ perhaps -- To increase or decrease by one variable . stay Python There is no such operator in . This error occurs in the following code :
spam = 1 spam++
Write it correctly :
spam = 1 spam += 1
17、 Forget to add... For the first parameter of the method self Parameter result “TypeError: myMethod() takes no arguments (1 given) ” This error occurs in the following code :
class Foo(): def myMethod(): print('Hello!') a = Foo() a.myMethod()