Type and Value Errors
TypeError reports that an operation received an unsuitable kind of value, while ValueError reports that an accepted kind contained an unacceptable value. You will diagnose operators, function calls, conversions, mixed collections, and unpacking without changing the intended meaning of the data.
TypeError and ValueError both report that an operation cannot use the value
it received. They differ in why the value is unsuitable.
int(None)
int() cannot convert None to an integer, so Python raises TypeError. The
kind of value is unsuitable for this conversion.
int("eight")
int() accepts strings, but "eight" does not contain a valid integer
representation. Python therefore raises ValueError. The kind of value is
accepted, but this particular value cannot be converted.
This distinction directs the first debugging question: did the operation receive the wrong kind of value, or did it receive an accepted kind containing an unacceptable value?
TypeError Points to an Incompatible Operation
A type describes the operations a value supports. Addition works between two integers:
It also joins two strings:
The same + symbol represents different operations for these types. Mixing an
integer and a string does not select a meaningful operation:
total = 8 + "6"
Python reports:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
The word operand means a value on which an operator acts. In 8 + "6",
the operands are 8 and "6". The message identifies both of their types.
Do not decide that one operand must always be converted to match the other. First determine the intended meaning. A numeric total needs two numbers:
total = 8 + int("6")
A text label needs an explicit string representation:
label = "score: " + str(8)
The intended operation determines the suitable conversion.
Functions Also Enforce Type Requirements
len() counts items in a collection or characters in a string:
An integer does not contain a sequence of items:
len(10)
Python reports:
TypeError: object of type 'int' has no len()
Function calls can also raise TypeError when their arguments do not match the
function definition:
The function requires two arguments but receives one. The error concerns the shape of the call rather than arithmetic:
TypeError: mean() missing 1 required positional argument: 'right'
When reading a TypeError, name the operation first: addition, division,
length, a function call, or another specific action. Then inspect the values or
arguments supplied to that operation.
ValueError Points to an Unacceptable Value
A function can accept a type while rejecting some values of that type.
int() accepts a string when the text represents an integer:
It cannot interpret arbitrary text as an integer:
count = int("twelve")
Python reports:
ValueError: invalid literal for int() with base 10: 'twelve'
A literal is text written directly in code to represent a value. In this
message, Python is explaining that "twelve" is not valid base-ten integer
text.
Even numeric-looking text can request the wrong conversion:
temperature = int("18.5")
The decimal point makes "18.5" unsuitable for direct conversion with
int(). If fractional values are allowed, use float():
temperature = float("18.5")
Choosing float() is correct only if the program's rules permit fractional
temperatures. Removing the decimal part merely to silence the error could
change the meaning of the input.
Unpacking Requires the Expected Number of Values
Tuple and list unpacking can also raise ValueError:
left, right = [3, 5, 7]
Both names are valid and the list type supports iteration. The problem is the number of values:
ValueError: too many values to unpack (expected 2)
The assignment expects exactly two items but receives three. The repair depends on the intended structure:
left, middle, right = [3, 5, 7]
or:
left, right = [3, 5]
Changing the code requires knowing whether the input has an extra item or the assignment omitted a name.
Inspect the Value Immediately Before Failure
Collections can carry an unsuitable value through several successful iterations:
The additions involving 2 and 4 succeed. The third addition receives a
string and raises TypeError.
Inspect the changing value and its type immediately before the failing operation:
Find the first incompatible value
Run the program, inspect each value and type, then replace the text value with a number.
Ready to run.
This temporary output tests the assumption that every item is numeric. It finds the first value that breaks the assumption without changing the calculation itself.
Convert Where External Text Enters
Text commonly enters a program from a form, command line, file, or network response. Convert it near that boundary:
Keeping both names makes the change explicit: score_text is the original
string, while score is the converted integer.
Conversion can itself fail when the text is malformed. A later lesson shows how to handle an expected conversion failure. During debugging, first inspect the original text rather than repeatedly converting it in unrelated parts of the program.
Exercise: Convert before dividing
Edit the code so it prints 4.0.
Create a numeric score
Ready to run.
HintConvert at the input boundary
Use int(score) to create a numeric value before dividing.
SolutionConvert, then divide
Write print(int(score) / 2). int(score) produces the integer 8, and
division produces the float 4.0.
Exercise: Distinguish type from value
Which expression raises ValueError rather than TypeError?
Select one choice, then check.
HintSeparate kind from content
int() can convert some strings, but it cannot convert None or a list.
SolutionInvalid integer text raises ValueError
int("eight") receives an accepted kind of input—a string—but its contents
do not represent an integer. None and [8] are unsuitable input types for
int(), so they raise TypeError.
Exercise: Choose a conversion that preserves meaning
Repair the program so it prints 9.25.
Keep the fractional temperature
Ready to run.
HintThe value is not a whole number
Convert the text with float() rather than int().
SolutionConvert the text to a float
Change the conversion to temperature = float(temperature_text). The value
becomes 18.5, and dividing it by two produces 9.25.
Exercise: Read a function-call TypeError
This call fails:
What is missing?
Select one choice, then check.
HintMatch arguments to parameters
The function definition has two required parameters.
SolutionThe right argument is missing
The argument 8 is assigned to left, but the call supplies no argument for
right. Calling mean(8, 6) would provide both required values.
Exercise: Repair an unpacking ValueError
Repair the assignment so the program prints 5.
Match three values with three names
Ready to run.
HintPreserve the middle item
Add a name between left and right.
SolutionUnpack all three positions
Write:
The number of target names now matches the number of values, and middle
receives 5.
Match the Operation, Type, and Particular Value
When Python reports TypeError or ValueError:
- name the operation or function call that failed;
- inspect the values and arguments supplied to it;
- use
type()when the kind of a value is uncertain; - for
TypeError, compare the received types with what the operation accepts; - for
ValueError, inspect the content, range, or number of values; - convert or restructure the data only after confirming the intended meaning.
A successful conversion is not enough if it changes the meaning of the input. The repair must satisfy both Python's requirements and the program's rules. The next lesson distinguishes missing positions in sequences from missing keys in dictionaries.