Summary of the most common mistakes made by Python beginners

  • 2020-05-30 20:26:55
  • OfStack

preface

Python for its simple syntax format in sharp contrast with other languages, beginners the most problems is not in accordance with the rules to write Python, even have a programmer programming experience, also easy to write Python according to the inherent thinking and syntax format code, this site to share before the 1 piece "Python beginners a few mistakes easily summarize", but not enough comprehensive summary, recently saw a foreign guy 1 are summarized some of the mistakes you make, 16 Common Python Runtime Errors Beginners Find, I simply translated it and added some understanding to the original, hoping that you can avoid these pits.

0. Forget the colon

Forget to add ":" to if, elif, else, for, while, class, def statements


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

Result: SyntaxError: invalid syntax

1. Misuse of "=" for equivalence comparison

"=" is an assignment operation, and "==" is used to determine whether two values are equal.


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

Result: SyntaxError: invalid syntax

2. Use the wrong indentation

Python USES indentation to distinguish code blocks. Common errors:


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

Cause: IndentationError: unexpected indent . Each line of code in the same block must be indent by 1


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

Cause: IndentationError: unindent does not match any outer indentation level . When the block ends, the indentation returns to its original position


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

Cause: IndentationError: expected an indented block , ":" should be followed by indentation

3. Variables are not defined


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

Cause: NameError: name 'spam' is not defined

4, get the list element index location forget to call the len method

When getting an element by index position, forget to use the len function to get the length of the list.


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

Cause: 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, the way to write Pythonic is enumerate


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

5. Modify the string

String 1 sequence object, support the index to get elements, but it is different from the list object, string is immutable object, do not support modification.


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

Cause: TypeError: 'str' object does not support item assignment The correct approach would be:


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

6, string and non - string connection


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

Cause: 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 a formatted form of a string


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

7. Using the wrong index location


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

Cause: IndexError: list index out of range

The index of the list object starts at 0, and the third element should be accessed using spam[2]

8. Use nonexistent keys in the dictionary


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

Cause: 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. The function is used before local variable assignment


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

Cause: IndentationError: unindent does not match any outer indentation level0

When a function has a variable with the same name as a global scope, it looks for the variable in LEGB's order, and if a variable with the same name is also defined in a local scope inside the function, it no longer looks in an external scope. So, someVar is defined in the myFunction function, so print(someVar) is no longer looking outside, but print is not assigned, so UnboundLocalError appears

11. Use "++" to reduce "--"


spam = 0
spam++

Haha, Python has no auto-increment and auto-decrement operators, so if you are switching from C or Java, you should be careful. 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()

Cause: TypeError: method1() takes 0 positional arguments but 1 was given

method1 is a member method of Foo class. This method does not accept any arguments. Calling a.method1 () is equivalent to calling Foo.method1 (a), but method1 does not accept any arguments, so it is wrong. The correct way to call it is Foo.method1 ().

It is important to note that the above code is based on Python3. In Python2, even the same code has not a single error, especially in the last example.

conclusion


Related articles: