For Pythoner beginners, running code during the learning process is more or less error-prone, which may seem taxing at first. With the accumulation of code, practice makes perfect and you can quickly locate the problem source if you encounter some runtime errors. Here are 17 common mistakes to help you out.
If, for, def, elif, else, class, etc. : “SyntaxError: invalid syntax”
if spam == 42 print('Hello! ')Copy the code
2, using = instead of == also causes “SyntaxError: invalid syntax” = to be the assignment operator and == to be the comparison operator. This error occurs in the following code:
if spam = 42: print('Hello! ')Copy the code
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 indentation increment is only used to: After the closing statement, which must then revert to the previous indentation format. This error occurs in the following code:
print('Hello! ') print('Howdy! ')Copy the code
Or:
if spam == 42: print('Hello! ') print('Howdy! ')Copy the code
4. Forgetting to call len() in a for loop
TypeError: ‘list’ object cannot be interpreted as an integer
Usually you want to iterate over a list or string by index, calling the range() function. Remember to return len instead of the list.
This error occurs in the following code:
spam = ['cat', 'dog', 'mouse']
for i in range(spam):
print(spam[i])
Copy the code
TypeError: ‘STR’ object does not support item Assignment ‘TypeError:’ STR ‘object does not support item Assignment’ string is an immutable data type.
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)
Copy the code
The right thing to do is:
spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)
Copy the code
TypeError: Can’t convert ‘int’ object to STR IMPLICITLY error TypeError: Can’t convert ‘int’ object to STR
numEggs = 12
print('I have ' + numEggs + ' eggs.')
Copy the code
The right thing to do is:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')
numEggs = 12
print('I have %s eggs.' % (numEggs))
Copy the code
SyntaxError: EOL while scanning String literal “SyntaxError: EOL while scanning string literal” error occurs in the following code:
print(Hello! ') print('Hello!) myName = 'Al' print('My name is ' + myName + . How are you? ')Copy the code
8. “NameError: name ‘fooba’ is not defined” is caused by incorrect spelling of variable or function name.
Foobar = 'Al' print('My name is' + fooba) spam = ruond(4.2) spam = Round(4.2)Copy the code
AttributeError: ‘STR’ object has no attribute ‘lowerr’
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()
Copy the code
IndexError: List index out of range
spam = ['cat', 'dog', 'mouse']
print(spam[6])
Copy the code
Error KeyError: ‘spam’ with a dictionary key that does not exist
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])
Copy the code
12, “SyntaxError: invalid syntax” may not be used as a variable name when attempting to use a Python keyword.
class = 'algebra'
Copy the code
Python3 keywords 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
Use value-added operators in a defined variable
Cause “NameError: Name ‘foobar’ is not defined”
Do not use 0 or an empty string as an initial value when declaring a variable, as a statement of spam += 1 using the increment operator equals 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
Copy the code
14. Using a local variable in a function before defining a local variable causes UnboundLocalError: Local variable ‘foobar’ referenced before Assignment “It is complicated to use a local variable in a function that also has a global variable of the same name. If anything is defined in a function, it’s local if it’s only used in a function, and global if it’s not. This means you can’t use it as a global variable in a function before you define it. This error occurs in the following code:
someVar = 42
def myFunction():
print(someVar)
someVar = 100
myFunction()
Copy the code
15. Attempts to create a list of integers using range() result in TypeError: 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
Copy the code
Correct way to write:
spam = list(range(10))
spam[4] = -1
Copy the code
(Note: Spam = range(10) works in Python 2 because range() returns a list, but in Python 3 it does.)
16. There is no ++ or — increment and decrement operator. If you’re used to other languages such as C++, Java, PHP, etc., you might want to try using ++ or — incrementing or decrement a variable. There is no such operator in Python. This error occurs in the following code:
spam = 1
spam++
Copy the code
Correct way to write:
spam = 1
spam += 1
Copy the code
TypeError: myMethod() takes no arguments (1 given) TypeError: myMethod() takes no arguments (1 given)
class Foo(): def myMethod(): print('Hello! ') a = Foo() a.myMethod()Copy the code