This guide explains type() Function: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
type(value) returns the type of an object. It is useful when debugging or learning how Python stores values; it is not a replacement for understanding what a value means in your application.
When You Would Use This
Inspecting inputs clarifies why a text price cannot be multiplied like a numeric price.
Step-by-Step Example
product_name = "Notebook"
quantity = 5
unit_price = 2.75
print(type(product_name).__name__)
print(type(quantity).__name__)
print(type(unit_price).__name__)
How the Example Works
The displayed type names are str, int, and float. .__name__ extracts a readable class name; calling type() alone displays the class object representation.
Example Output
str
int
float
Try It Yourself
Check type(True) and type(None) and explain why the results are different.
Common Beginner Mistakes
- Confusing the class of an object with the spelling of its variable name.
- Using exact
type()comparisons whereisinstance()would accommodate subclasses. - Assuming a value with a numeric-looking string has type
int.
Key Takeaways
type(value)returns the type of an object.- The displayed type names are
str,int, andfloat. - Avoid this mistake: Confusing the class of an object with the spelling of its variable name.