Home > Article > Backend Development > Take a look at some mistakes that even Python experts can't write
For those who are just getting started with Pythonista, they will more or less encounter some errors when running the code during the learning process, and it may seem difficult at first. As the amount of code accumulates, practice makes perfect and you can quickly locate the original problem when encountering some runtime errors. Below we have compiled some 17 common errors. When the code you write does not have these errors, your Python skills will reach a higher level. In other words, when you become a qualified Python developer, you may make mistakes like " can't even write ".
Free learning recommendation: python video tutorial
1,
Forget about if, for , adding :
at the end of declarations such as def, elif, else, class, etc. will result in "SyntaxError: invalid syntax" as follows:
if spam == 42 print('Hello!')
2,
Using = instead of ==
will also cause "SyntaxError: invalid syntax"
= is the assignment operator and == is the equal comparison operation. This error occurs in the following code:
if spam = 42: print('Hello!')
3,
Incorrect use of indentation
results in "IndentationError: unexpected indent", " IndentationError: unindent does not match any outer indetation level" and "IndentationError: expected an indented block"
Remember that the indentation increase is only used after the statement ending with:, and then the previous indentation must be restored Format. This 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 statement
#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 the list. This error occurs in the following code:spam = ['cat', 'dog', 'mouse'] for i in range(spam): print(spam[i])
5,
Trying to modify the value of stringresults in "TypeError: 'str' object does not support item assignment" string is an immutable data type. This 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,
Attempting to concatenate a non-string value with a stringresults 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,
Forgot at the beginning and end of the string Adding quotes results in "SyntaxError: 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,
Spelling errors in variable or function names results in "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.
The method name is spelled incorrectlyleading to "AttributeError: 'str' object has no attribute 'lowerr'"This error occurs in the following code :spam = 'THIS IS IN LOWERCASE.' spam = spam.lowerr()
10,
The reference exceeds the maximum index of list resulting in "IndexError: list index out of range"This The 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 key cannot be used as a variable name. This error occurs in the following code:class = 'algebra' Python3的关键字有: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,
In a Using the value-added operator when defining a new variable results in "NameError: name 'foobar' is not defined" Do not use 0 or an empty string as the initial value when declaring a variable. Use it automatically. The sentence spam = 1 of the increment operator is equal to spam = spam 1, which means that spam needs to specify a valid initial value. This error occurs in the following code:spam = 0 spam += 42 eggs += 42
14,
Use local variables in the function before defining them (at this time there are A global variable with the same name as a local variable exists) Causes "UnboundLocalError: local variable 'foobar' referenced before assignment" When a local variable is used in a function and a global variable with the same name exists at the same time It's very complicated. The usage rules are: if anything is defined in a function, if it is only used in the function, it is a local variable, otherwise it is a global variable. This means that you cannot 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,
Trying to use range() to create a list of integers results "TypeError: 'range' object does not support item assignment"Sometimes you want to get an ordered list of integers, so range() seems like a good way to generate this list. However, you need to remember that range() returns a "range object", not the actual list value. This error occurs in the following code:spam = range(10) spam[4] = -1 正确写法: spam = list(range(10)) spam[4] = -1
(注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就会产生以上错误)
16、
不存在 ++ 或者 -- 自增自减操作符。
导致“SyntaxError: invalid syntax”
如果你习惯于例如 C++ , Java , PHP 等其他的语言,也许你会想要尝试使用 ++ 或者 -- 自增自减一个变量。在Python中是没有这样的操作符的。
该错误发生在如下代码中:
spam = 1spam++ 正确写法: spam = 1spam += 1
17、
忘记为方法的第一个参数添加self参数
导致“TypeError: myMethod() takes no arguments (1 given)”
该错误发生在如下代码中:
class Foo(): def myMethod(): print('Hello!') a = Foo() a.myMethod()
相关免费学习推荐:python教程(视频)
The above is the detailed content of Take a look at some mistakes that even Python experts can't write. For more information, please follow other related articles on the PHP Chinese website!