Python common beginners mistakes

In this post:

In section References you can find information about all Built-in Exceptions like: ValueError, TypeError, AttributeError and so on..

AttributeError: 'dict' object has no attribute 'dumps'

It's a common mistake to use a reserved word as a variable name. This leads to error: AttributeError because the variable has different type and not the expected one. For example:

import json

json = {'team': 'Brazil', 'position': 1, 'host': True, 'lastGame': 'Win'}
dictToJson = json.dumps(json)
print(dictToJson)

This code produce error:

AttributeError: 'dict' object has no attribute 'dumps'

Because we are importing module json and then we use it for a variable name. In order to solve it we need to choose a better variable name:

import json

dict = {'team': 'Brazil', 'position': 1, 'host': True, 'lastGame': 'Win'}
dictToJson = json.dumps(dict)
print(dictToJson)

TypeError: 'int' object is not callable

This error is caused again by the similar reason - if it is used a reserved name of a function like sum. This error can be prevented by using special word del:

  • del - Deletion of a name removes the binding of that name from the local or global namespace

So the code below will produce error:

sum = 0

for i in range(102):
    res = sum(range(i))

And the error is:

TypeError: 'int' object is not callable

It's better to be careful with the names and to check build-in types and functions, and keywords. Adding del sum will solve the problem too:

sum = 0
del sum

for i in range(102):
    res = sum(range(i))

TypeError: Can't convert 'int' object to str implicitly

Another common problem in Python(and not only) for beginners is type conversion and working with multiple types. For example if you want to apply sum operator to string and int:

numberString = 'text' + 5

The code above is raising error:

TypeError: Can't convert 'int' object to str implicitly

In order to workaround this error you will need to convert your variable explicitly:

numberString = 'text' + str(5)

ValueError: invalid literal for int() with base 10: '11a'

Working with numbers like integers and floats can result in ValueError. This means that you are treating something as a number which is not number. For example explicitly converting non number to int:

c = "11a"
print(int(c))

And the error is:

ValueError: invalid literal for int() with base 10: '11a'y

There are many ways to solve this problem. A classic way is to check the string is it a number?:

c = "11a"
print(c.isdigit())

result:

False

IndexError: list index out of range

Working with collection and indexes often could end in index out of range:

mylist = [1, 2, 3]
print(mylist[3])

And the error is:

IndexError: list index out of range

You can preparare for this situation by catching potential errors. This code catch the error and return the last element of the this list:

try:
    mylist = [1, 2, 3]
    print(mylist[3])
except IndexError:
    print(mylist[-1])

result:

3

Handling errors with try .. except

One of the ways to secure your code against unexpected errors is by handling the problematic situations and enclose them in try..except blocks:

The following code will raise two errors: ValueError, TypeError - of course the program will end at the first line:

print(int('11a'))
numberString = 'text' + 5

You can catch the error and continue your program by:

try:
    print(int('11a'))
    numberString = 'text' + 5
except (ValueError, TypeError) as e:
    pass

Note that the second line of code:

numberString = 'text' + 5

will not execute. Because after the first error the code will go to except clause.

Reference

Related Article