Type Errors
A TypeError means an operation received a value of an unsuitable type.
Python is not saying the value is bad in every context. It is saying this operation does not know what to do with that kind of value.
total = 8 + "6"
Addition works for two numbers:
8 + 6
Concatenation works for two strings:
"8" + "6"
But 8 + "6" mixes the two meanings.
Read the operation
Most type errors become clearer when you name the operation:
The operation is division. Division expects numbers. A string can contain a digit character, but it is still text.
Conversion should be explicit. Do it near the boundary where text enters the program.
Function calls can have type errors
len(10)
len works on containers and strings. An integer has no length. The useful
question is:
What did I believe this value was?
Inspect the value before the failing operation
Ready to run.
The type output is not the solution by itself. It confirms the assumption
being tested.
Type errors in collections
Collections often hide mixed types:
The loop works for 2 and 4. It fails when value becomes "6".
Small inspection can find the first bad value:
Later, NumPy arrays and data tables will make type consistency even more important. The habit starts here.
Edit the code so it prints 4.0.
Convert before dividing
Ready to run.
HintConvert at the boundary
score is text. Use int(score) to create a numeric value before division.
SolutionConvert, then divide
Change the print expression to int(score) / 2. The conversion produces the
integer 8, and / produces the float 4.0.