Summary of 17 common rookie mistakes when running Python

  • 2020-04-02 09:37:27
  • OfStack

1) forgot to add at the end of if, elif, else, for, while, class,def declaration: (causes "SyntaxError: invalid syntax")
The error will occur in code like this:
 
if spam == 42 
print('Hello!') 

2) use = instead of == (cause "SyntaxError: invalid syntax")
= is the assignment operator and == is the equals comparison operation. This error occurs in the following code:
 
if spam = 42: 
print('Hello!') 

3) incorrect use of indentation. (cause "IndentationError: unexpected indent" and "IndentationError: unindent does not match any outer indetation level" and "IndentationError: expected an indented block")
Remember that indentation increments are used only after statements that end in:, and then you must revert to the previous indentation format. This error occurs in the following code:
 
print('Hello!') 
print('Howdy!') 
 Or:  
if spam == 42: 
print('Hello!') 
print('Howdy!') 
 Or:  
if spam == 42: 
print('Hello!') 

4) forget to call len() in the for loop statement (resulting in "TypeError: 'list' object cannot be interpreted as an integer")
Usually you want to iterate over the elements of a list or a string by index, which involves 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) try to modify the value of string (cause "TypeError: 'STR' object does not support item assignment")
String is an immutable data type, and the error occurs in the following code:
 
spam = 'I have a pet cat.' 
spam[13] = 'r' 
print(spam) 

And you actually want to do this:
 
spam = 'I have a pet cat.' 
spam = spam[:13] + 'r' + spam[14:] 
print(spam) 

6) try to connect a non-string value to a string (resulting 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 you actually want to do this:
 
numEggs = 12 
print('I have ' + str(numEggs) + ' eggs.') 
 Or:  
numEggs = 12 
print('I have %s eggs.' % (numEggs)) 

7) forgetting to put quotes at the beginning and end of the string (resulting in "SyntaxError: EOL while scanning string literal")
This error occurs in the following code:
 
print(Hello!') 
 or : 
print('Hello!) 
 or : 
myName = 'Al' 
print('My name is ' + myName + . How are you?') 

8) spelling error of variable or function name (causes "NameError: name 'fooba' is not defined")
This error occurs in the following code:
 
foobar = 'Al' 
print('My name is ' + fooba) 
 or : 
spam = ruond(4.2) 
 or : 
spam = Round(4.2) 

9) method name spelling error (causes "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 list maximum index (resulting in "IndexError: list index out of range")
This error occurs in the following code:
 
spam = ['cat', 'dog', 'mouse'] 
print(spam[6]) 

11) use a nonexistent dictionary key value (causes "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 using the Python keyword as the variable name (cause "SyntaxError: invalid syntax")

Python key cannot be used as a variable name. This error occurs in the following code:

class = 'algebra' 

Python3's 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 the yield

13) use the value increment operator in a defined new variable (resulting in "NameError: name 'foobar' is not defined")

Do not use 0 or an empty string as the initial value when declaring a variable. The use of the auto-increment operator spam += 1 equals spam = spam + 1 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 functions before defining local variables (where a global variable with the same name as the local variable exists) (cause "UnboundLocalError: local variable 'foobar' referenced before assignment")
It's complicated to use a local variable in a function that has a global variable of the same name. The rule is: if anything is defined in a function, it's local if it's only used in a function, and it's global if it's not.
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) try to create a list of integers using range() (causes "TypeError: 'range' object does not support item assignment")
Sometimes you want an ordered list of integers, so range() seems like a good way to generate that 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 

Maybe this is what you want to do:
 
spam = list(range(10)) 
spam[4] = -1 

(note: in Python 2 spam = range(10) is fine, because in Python 2 range() returns a list value, but in Python 3 the above error is generated.)
16) good in ++ or -- self - increase and self - decrease operators. (causes "SyntaxError: invalid syntax")
If you're used to other languages like C++, Java, PHP, etc., you might want to try using ++ or -- add and subtract a variable. There is no such operator in Python.
This error occurs in the following code:
 
spam = 1 
spam++ 

Maybe this is what you want to do:
 spam = 1 
spam += 1 

17) forgot to add the self parameter for the first argument of the method (causes "TypeError: myMethod() takes no arguments (1 given)")
This error occurs in the following code:
 
class Foo(): 
def myMethod(): 
print('Hello!') 
a = Foo() 
a.myMethod() 

Related articles: