Python Beginners Common Mistakes Detailed Explanation
- 2021-07-09 08:29:02
- OfStack
Preface
Python is in sharp contrast with other languages with its easy-to-understand grammatical format, The most common problem encountered by beginners is that they don't write according to Python rules. Even programmers with programming experience are easy to write Python code according to the inherent thinking and grammar format. A foreign boy summed up some mistakes that everyone often makes. I translated him and added my understanding on the original basis, hoping to make you avoid these pits.
0. Forgot to write a colon
Forgot to add ":" after if, elif, else, for, while, class and def statements
if spam == 42
print('Hello!')
Resulting in: SyntaxError: invalid syntax
1. Misuse "=" for equivalent comparison
"=" is an assignment operation, while determining whether two values are equal is "= ="
if spam = 42:
print('Hello!')
Resulting in: SyntaxError: invalid syntax
2. Use incorrect indentation
Python uses indentation to distinguish code blocks. Common wrong usage:
print('Hello!')
print('Howdy!')
Resulting in: IndentationError: unexpected indent. Each line of code in the same code block must keep an indentation of 1
if spam == 42:
print('Hello!')
print('Howdy!')
Resulting in: IndentationError: unindent does not match any outer indentation level. Indentation reverts to the original position after the end of the code block
if spam == 42:
print('Hello!')
Resulting in: IndentationError: expected an indented block, using indentation after ":"
3. Variables are not defined
if spam == 42:
print('Hello!')
Resulting in: NameError: name 'spam' is not defined
4. Obtain the index position of list elements and forget to call len method
When getting elements by index position, forget to use len function to get the length of the list.
spam = ['cat', 'dog', 'mouse']
for i in range(spam):
print(spam[i])
Causes: TypeError: range () integer end argument expected, got list. The correct approach is:
spam = ['cat', 'dog', 'mouse']
for i in range(len(spam)):
print(spam[i])
Of course, Pythonic is written in enumerate
spam = ['cat', 'dog', 'mouse']
for i, item in enumerate(spam):
print(i, item)
5. Modify the string
String is a sequence object, which supports getting elements by index, but it is different from list object, and string is an immutable object, which does not support modification.
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)
Resulting in: TypeError: 'str' object does not support item assignment the correct approach should be:
if spam = 42:
print('Hello!')
0
6. String and non-string concatenation
if spam = 42:
print('Hello!')
1
Resulting in: TypeError: cannot concatenate 'str' and 'int' objects
When a string is concatenated with a non-string, the non-string object must be cast to a string type
if spam = 42:
print('Hello!')
2
Or use the formatted form of a string
num_eggs = 12
print('I have %s eggs.' % (num_eggs))
7. Use the wrong index location
if spam = 42:
print('Hello!')
4
Resulting in: IndexError: list index out of range
The index of the list object starts from 0, and the third element should be accessed using spam [2]
8. Use non-existent keys in dictionaries
if spam = 42:
print('Hello!')
5
You can use [] to access key in the dictionary object, but if the key does not exist, it will result in: KeyError: 'zebra'
The correct way is to use the get method
if spam = 42:
print('Hello!')
6
When key does not exist, get returns None by default
9. Use keywords as variable names
if spam = 42:
print('Hello!')
7
Resulting in: SyntaxError: invalid syntax
Keywords are not allowed as variable names in Python. Python3 1 has a total of 33 keywords.
>>> import keyword
>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
10. Local variables in functions are used before assignment
if spam = 42:
print('Hello!')
9
Resulting in: UnboundLocalError: local variable 'someVar' referenced before assignment
When a function has a variable with the same name as the global scope, it will look for the variable in the order of LEGB. If a variable with the same name is defined in the local scope inside the function, it will no longer look for it in the external scope. Therefore, someVar is defined in the myFunction function, so print (someVar) is no longer looked up outside, but the variable has not been assigned at print, so UnboundLocalError appears
11. Use self-increasing "+ +" and self-decreasing "-"
spam = 0
spam++
Haha, there is no self-increasing and self-decreasing operator in Python. If you switch from C and Java, you should pay attention. You can use "+ =" instead of "+ +"
spam = 0
spam += 1
12. Incorrectly calling a method in a class
class Foo:
def method1():
print('m1')
def method2(self):
print("m2")
a = Foo()
a.method1()
Resulting in: TypeError: method1 () takes 0 positional arguments but 1 was given
method1 is a member method of the Foo class, which does not accept any parameters. Calling a. method1 () is equivalent to calling Foo. method1 (a), but method1 does not accept any parameters, so an error is reported. The correct way to call should be Foo. method1 ().
It should be noted that the above codes are all based on Python3, and even the same codes in Python2 have different errors, especially the last example.