Understanding Python's type() Function
This article is a complementary resource to the Learn Python Basics course.
This article is a complementary resource to the Learn Python Basics course.
The
type()
function in Python tells you the type of data you're working with. This is useful for confirming whether a value is a number, string, boolean, or another data type. For example,
# Check the type of the word "Pikachu"
data_type = type("Pikachu")
print(data_type)
Output
<class 'str'>
Here,
type("Pikachu")
shows that
"Pikachu"
is a string (str
).
Let's check the types of various other values:
# Check the type of different data
data_type_int = type(65)
data_type_float = type(65.50)
data_type_bool = type(True)
print(f"65 is of type {data_type_int}")
print(f"65.50 is of type {data_type_float}")
print(f"True is of type {data_type_bool}")
Output
65 is of type <class 'int'> 65.50 is of type <class 'float'> True is of type <class 'bool'>
Suppose you are given daily sales data in the following format:
sales_data = [500, 500, "no sale", 700, "nosale", 200, "no sale"]
Your goal is to calculate the total sales, but the data includes both valid numbers and invalid entries (like
"no sale"
). You can use the
type()
function to ensure that only valid numbers are added to the total.
# Sales data (includes valid numbers and invalid entries)
sales_data = [500, 500, "no sale", 700, "nosale", 200, "no sale"]
# Initialize total sales to 0
total_sales = 0
# Process each entry in the sales data
for sale in sales_data:
if type(sale) == int or type(sale) == float:
total_sales += sale # Add valid numbers to total sales
# Output the total sales
print(f"Total Sales: ${total_sales}") # Total Sales: $1900
This is just a simple example. In practice, there will be many more complex scenarios where data can come in different formats or types, and
type()
will be useful for validation.
Knowing the type of data you're working with is crucial because: