AttributeError¶
AttributeError: XXX object has no attribute YYY¶
An attempt was made to apply a method (indicated by YYY) to the object XXX but the method does not exist for the type of XXX.
A particular case occurs when a module is imported with the import statement and an attempt is made to call a function of this module that does not exist in the file.
Examples
In this example, an attempt is made to apply the replace method to a list but this method does not exist for this type.
1def canvia_0_per_1(llista):
2 i=0
3 for i in range(len(llista)):
4 if llista[i]==0:
5 llista = llista.replace(0,1)
6
>>> lnum = [0,2,5,0,2,0]
>>> objecthasnoattribute1.canvia_0_per_1(lnum)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "objecthasnoattribute1.py", line 5, in canvia_0_per_1
llista = llista.replace(0,1)
AttributeError: 'list' object has no attribute 'replace'
In this example filename is a string parameter that contains the name of a file. The notation filename.txt contains a string object followed by a dot and, therefore, is interpreted by Python as a call to the txt method which must be a string method, but this method does not exist and gives an error.
1def cost_total(nomfitxer):
2 f = open(nomfitxer.txt,'r')
3 ctotal = 0
4 for linia in f:
5 ldades = linia.split()
6 unitats = int(ldades[1])
7 cost = float(ldades[2])
8 ctotal = ctotal + unitats * cost
9 f.close()
10 return ctotal
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "objecthasnoattribute2.py", line 2, in cost_total
f = open(nomfitxer.txt,'r')
AttributeError: 'str' object has no attribute 'txt'
This example corresponds to the particular case mentioned above. The inventory module is imported and then the module function called total is called. The error indicates that there is no function in the ``inventory.py
>>> import inventari
>>> inventari.total()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'total'
FileNotFoundError¶
FileNotFoundError: [Errno 2] No such file or directory: XXX¶
An attempt was made to open a file named XXX for reading that does not exist.
Example
In this example, line 2 attempts to open the file inventario.txt for reading, but Python cannot find this file. Often the problem is that it is not the correct name or the file is not in the directory (folder) where we are located.
1def cost_total():
2 f = open('inventari.txt','r')
3 ctotal = 0
4 for linia in f:
5 ldades = linia.split()
6 unitats = int(ldades[1])
7 cost = float(ldades[2])
8 ctotal = ctotal + unitats * cost
9 f.close()
10 return ctotal
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "filenotfound1.py", line 2, in cost_total
f = open('inventari.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'inventari.txt'
ImportError¶
ImportError: No module named XXX¶
An attempt was made to import a module named XXX.py* but no file with this name exists.
Example
In this example, we try to import the conversions.py module but it gives an error because Python cannot find this file. Often the problem lies in the fact that it is not the correct name or the file is not in the directory (folder) where we are located.
>>> import conversions
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'conversions'
IndentationError¶
IndentationError: expected an indented block¶
There are missing spaces in front of a statement that goes inside a code block in an if, while, for, etc.
Example
In this example, the statement that must be executed if the condition is met cannot go at the same height as the if.
1def descompte1(imp,iva):
2 total = imp + imp*iva/100.0
3 if total > 100:
4 total = total -5
5 return total
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "expectindent1.py", line 4
total = total -5
^
IndentationError: expected an indented block
IndentationError: unexpected indent¶
Excess spaces before a statement.
Example
In this example, line 3 has more spaces than necessary and should be at the height of the previous line.
1def descompte1(imp,iva):
2 total = imp + imp*iva/100.0
3 total = total -5
4 return total
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "unexpectindent1.py", line 3
total = total -5
^
IndentationError: unexpected indent
IndentationError: unindent does not match any outer indentation level¶
The spacing of a statement does not match any spacing level of the others.
Example
In this example, the statement on line 4 is not aligned with either line 1 or line 2 or 3. In this case, it should have one more space.
1def descompte1(imp,iva):
2 total = imp + imp*iva/100.0
3 total = total -5
4 return total
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "unindentdoesnotmatch1.py", line 4
return total
^
IndentationError: unindent does not match any outer indentation level
IndexError¶
IndexError: XXX index out of range¶
An attempt was made to access the position of a value (of the type indicated by XXX) using an index that is not within the allowed range.
Example
In this example, the function receives the string text as a parameter and assigns the length of this string to the variable ultima (line 2). Later (line 3) an attempt is made to access the position indicated by ultima which is outside the allowed range and gives an error. The indices of a string start from 0 and so the maximum allowed index is the length minus 1.
1def igualprimeraultima(text):
2 ultima = len(text)
3 if text[0] == text[ultima]:
4 return 'iguals'
5 else:
6 return 'diferents'
7
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "indexoutrange1.py", line 3, in igualprimeraultima
if text[0] == text[ultima]:
IndexError: string index out of range
KeyError¶
KeyError: XXX¶
An attempt was made to access a value in a dictionary through the key XXX but this key does not exist.
Example
In this example, the keys of the dictionary are the strings ‘BUS’, ‘BICING’ and ‘METRO’ and therefore the attempt to access through the key 12 gives an error.
>>> d = {'BUS':23,'BICING':35,'METRO':12}
>>> d[12]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 12
NameError¶
NameError: name XXX is not defined¶
A reference was made to a name (indicated by XXX) that Python does not know because it is not in the language or has not been defined.
Exemples
Calling a function with a different name than the one used in the definition. In this case, the call convseconds is incorrect because we have defined the function as conv_seconds.
1def conv_segons(h,m,s):
2 segons = h*3600+m*60+s
3 return segons
>>> from conversions import *
>>> convsegons(1,3,40)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'convsegons' is not defined
Using functions from an external module that has not been imported. In this case, the call to the sin function is incorrect because this function is in the math module and has not been imported. Once imported and called correctly, it works.
>>> sin(1.57)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sin' is not defined
>>> import math
>>> math.sin(1.57)
0.9999996829318346
SyntaxError¶
SyntaxError: invalid syntax¶
The syntax does not conform to Python writing rules.
Exemples
Using operators incorrectly. In this case, the expression that calculates 2 multiplied by the variable k is incorrect because the multiplication operator * is missing.
1def f(x,k):
2 num = 1 /(2*x+1)
3 y = num/(2k-1)
4 res = num/y
5 return y
6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "invalidsyntax1.py", line 3
y = num/(2k-1)
^
SyntaxError: invalid syntax
Use = instead of == to make comparisons.
1def es_parell(n):
2 if n%2 = 0:
3 return True
4 else:
5 return False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "invalidsyntax2.py", line 2
if n%2 = 0:
^
SyntaxError: invalid syntax
Not writting : at the end of the statements that require it (if, elif, else, for, while, def). In this example, they need to be put at the end of the if statement.
1def es_parell(n):
2 if n%2 == 0
3 return True
4 else:
5 return False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "invalidsyntax3.py", line 2
if n%2 == 0
^
SyntaxError: invalid syntax
Use a Python reserved word as a variable name (in this example in)
1def celsius_kelvin(c):
2 in = c + 273.15
3 return in
4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "invalidsyntax4.py", line 2
in = c + 273.15
^
SyntaxError: invalid syntax
SyntaxError: EOL while scanning string literal¶
Missing quotes (single or double, depending on the code) to open or close a string.
Example
En aquest exemple falta tancar la cometa de l´últim string a la línia 2.
1def genera_adreca(nom,cognom):
2 s = nom + '.' + cognom + '@estudiant.upc.edu
3 return s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "eolscanning1.py", line 2
s = nom + '.' + cognom + '@estudiant.upc.edu
^
SyntaxError: EOL while scanning string literal
SyntaxError: EOF while scanning triple-quoted string literal¶
Example
1def genera_adreca(nom,cognom):
2 """
3 >>> genera_adreca('pep','pepot')
4 'pep.pepot@estudiant.upc.edu'
5
6 s = nom + '.' + cognom + '@estudiant.upc.edu'
7 return s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "eolscanningtriple1.py", line 7
return s
^
SyntaxError: EOF while scanning triple-quoted string literal
TypeError¶
TypeError: Can’t convert XXX object to str implicitly¶
An attempt was made to use a string operation with some other data type (indicated by XXX)
Example
In this example, line 4 tries to concatenate an integer to the variable s that contains a string.
1def afegeix_bin(num):
2 s = '00'
3 if num >= 0:
4 s = s + 1
5 else:
6 s = s + '0'
7 return s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "cantconvertstr1.py", line 3, in afegeix_bin
s = s + 1
TypeError: Can't convert 'int' object to str implicitly
TypeError: unorderable types: XXX > YYY¶
An attempt was made to compare two different types (XXX and YYY indicate the types) that cannot be compared because they are not ordered between them.
Example
In this example the variable prod_code contains a string and an attempt is made to compare with an integer.
>>> codi_prod = '2'
>>> codi_prod > 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
TypeError: can only concatenate XXX (not YYY) to XXX¶
An attempt was made to concatenate values of two different types (indicated by XXX and YYY).
Example
In this example, the intersection function has been executed with the values ``list1=[1,2,3]`` and list2=[2,3,4,5]. On line 5, an attempt is made to concatenate to the variable lres, which is a list, a value from list1 that is an integer.
1def interseccio(llista1,llista2):
2 lres = []
3 for c in llista1:
4 if c in llista2:
5 lres = lres + c
6 return lres
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "canonlyconcat1.py", line 5, in interseccio
lres = lres + c
TypeError: can only concatenate list (not "int") to list
TypeError: XXX indices must be integers, not YYY¶
An attempt was made to access an element of an indexed type (such as a list)
Example
This example attempts to access a position in a string using another string. When an integer is used (in this case 12) the access is executed correctly.
>>> s = "Fonaments d'Informàtica"
>>> s['I']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>> s[12]
'I'
TypeError: unsupported operand type(s) for XXX: YYY and ZZZ¶
An attempt was made to apply an operator (indicated by XXX) to values of a type that does not accept this type of operation (indicated by YYY and ZZZ).
Exemples
In these examples, an attempt is made to apply numeric type operands (division, addition, and subtraction) to types that do not accept this type of operation such as strings or lists.
>>> s1 = '3'
>>> s2 = '7'
>>> s1/s2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'str'
>>> s1-2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> l = [2, 4, 5]
>>> 3.56+l
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'float' and 'list'
TypeError: bad operand type for unary XXX: YYY¶
An attempt was made to apply a unary operator (indicated by XXX) to a value that does not accept this type of operation (indicated by YYY).
Example
This example applies the sign change operation to a string, a type that does not accept this operation.
>>> s = '3'
>>> -s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary -: 'str'
TypeError: XXX object is not subscriptable¶
An attempt was made to access an element through an index to a value of a type (indicated by XXX) that does not accept indexing, or an attempt was made to obtain a slice of a type that does not accept the operation.
Example
In this example, the values taken by the variable i are integers, since they are generated from the for-in-range statement. On line 4 of the function, an attempt is made to access position 0 of the variable i, which gives an error because integers cannot be indexed.
1def comenca_vocal(llista):
2 n = 0
3 for i in range(len(llista)):
4 if i[0] in 'AEIOUaeiou':
5 n = n + 1
6 return n
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "objectnotsubscript1.py", line 4, in comenca_vocal
if i[0] in 'AEIOUaeiou':
TypeError: 'int' object is not subscriptable
TypeError: XXX missing YYY required positional argument: ZZZ¶
An attempt was made to call the function (indicated by XXX) with fewer parameters (indicated by YYY) than required. The name of the parameters is indicated by ZZZ.
Example
In this example, the conv_segons function is defined with three parameters but the call is only given two.
1def conv_segons(h,m,s):
2 segons = h*3600+m*60+s
3 return segons
>>> import conversions
>>> conversions.conv_segons(1,5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: conv_segons() missing 1 required positional argument: 's'
>>>
TypeError: XXX object cannot be interpreted as an YYY¶
A value or variable of type XXX has been used in a context where type YYY is required.
Example
In this example, on line 3, the range function requires an integer parameter and has been passed a list, instead of the length of the list, which is an integer.
1def suma_llista(l):
2 s = 0
3 for i in range(l):
4 s = s + l[i]
5 return s
>>> import cannotbeinterpreted
>>> cannotbeinterpreted.suma_llista([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "cannotbeinterpreted.py", line 3, in suma_llista
for i in range(l):
TypeError: 'list' object cannot be interpreted as an integer
TypeError: unhashable type: XXX¶
An attempt was made to use the data type XXX which is not immutable as a key in a dictionary.
Example
In this example, a dictionary is defined where the keys are tuples, but an attempt is made to check if a key exists that is a list, which is a mutable type and gives an error.
>>> d = {(1,2):'vermell',(5,5):'blau',(3,7):'blau'}
>>> llista = [2,3]
>>> llista in d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>
UnboundLocalError¶
UnboundLocalError: local variable xxx referenced before assignment¶
Inside a function, an attempt was made to access the value of a variable that has not been defined before.
Example
In this example, no value has been given to the variable com and an attempt has been made to access its value on line 3.
1def comissions(dep,pref):
2 if dep > 500000:
3 com = com + dep * 0.005
4 if pref > 500000:
5 com = com + pref * 0.03
6 return com
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "localvarrefbefore1.py", line 3, in comissions
com = com + dep * 0.005
UnboundLocalError: local variable 'com' referenced before assignment
ValueError¶
ValueError: could not convert XXX to YYY: ZZZ¶
An attempt has been made to convert from type XXX to type YYY with the value ZZZ, but the value does not have a suitable format for the conversion.
Example
In this example, an attempt is made to convert the string s to a real number, but since it contains a comma, the conversion cannot be carried out, since Python uses the dot to denote decimals and the float function does not know how to interpret the string as a real number. A string containing a dot is then assigned to it and the conversion is performed without problems.
>>> s = '276,25'
>>> float(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '276,25'
>>> s = '276.25'
>>> float(s)
276.25
ValueError: invalid literal for int() with base 10: XXX¶
An attempt was made to convert the value XXX to integer but this value does not have a suitable format in base 10.
Example
In this example the string s contains a period and therefore the format is incorrect as an integer. Later it is shown how when executing the conversion to float it does work, since the format is correct as a real, or if the string is assigned a value with only integers, the conversion to integer is also executed correctly.
>>> s = '276.25'
>>> float(s)
276.25
>>> s = '125.12'
>>> int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '125.12'
>>> float(s)
125.12
>>> s = '125'
>>> int(s)
125
ValueError: math domain error¶
An attempt was made to execute a mathematical operation with incorrect data.
Example
In this example, we try to call the function f with the value 0 for the parameter x, which, within the function, tries to calculate the square root of -1 and gives an error because it is a negative number.
1import math
2
3def f(x):
4 return math.sqrt(x-1)+math.sin(x)
>>> import funcio
>>> funcio.f(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "funcio.py",line 4, in f
return math.sqrt(x-1)+math.sin(x)
ValueError: math domain error