Inspecting Types
A type tells you what kind of value Python is working with.
Use type() to inspect a value:
Output:
<class 'int'>
<class 'float'>
<class 'str'>
This is useful because values that look similar can behave differently.
Same Print, Different Type
These two values print similarly:
But their types differ:
One is an integer. The other is a string.
Debugging with type()
Suppose this code surprises you:
Output:
81
Inspecting the type explains why:
print(type(value))
The value is a string, so + joins text.
Inspect before guessing
The output makes sense once you inspect the type.
Ready to run.
Types You Have Seen
| Type display | Common name | Example |
|---|---|---|
<class 'int'> | integer | 8 |
<class 'float'> | float | 8.0 |
<class 'str'> | string | "hello" |
<class 'bool'> | boolean | True |
<class 'NoneType'> | None type | None |
The display format looks a little formal. Do not worry about the word class
yet. For now, read it as "the kind of value."
Printed Values Can Hide Types
Do not use type() as a substitute for understanding. It is a debugging tool.
Use it when behavior surprises you.
What type does type() return for this value?
type("loss")
Answer it first, then check.
HintUse the quotation marks
Quotation marks create a text value. Recall Python's short type name for a string.
SolutionThe type is str
"loss" is text, so type("loss") returns <class 'str'>. The short type
name is str, meaning string.
Check the Type When Meaning Is Unclear
When Python behavior surprises you, inspect the type. Many bugs begin as "I thought this was a number, but it is text."