Inspecting Data with type()
As you write larger and more complex programs, you will sometimes lose track of what data type a variable is holding especially when data is passed around or modified.
Fortunately, Python has a built-in helper function called type() that allows you to ask Python directly: "What kind of data box am I looking at right now?"
When you pass a variable or a value into type(), Python returns the data type class of that object.
Let's test it out in code:
When you run this script, your terminal won't just print the values; it will print their classes like <class 'int'>, <class 'float'>, <class 'str'>, and <class 'bool'>. This is an incredible debugging tool when your code behaves unexpectedly!
The Data Type Mismatch Problem
Knowing about data types isn't just theory it prevents your programs from crashing.
One of the most common beginner mistakes is trying to combine incompatible data types together. For example, what happens if you try to join a string of text with an integer number in a print statement using a plus sign (+)?
Run this code to see what happens:
Boom! Python crashes with a brand-new error:
TypeError: can only concatenate str (not "int") to str
Python is telling you: "I can glue text to text, and I can add numbers to numbers, but I refuse to glue a number directly onto a sentence without instructions."
To fix this problem, we need a way to change data types on the fly. That process is called Type Conversion.
Casting Gotchas: The ValueError
Type conversion is powerful, but it is not magic. Python will crash if you ask it to do something that mathematically or logically makes no sense.
For example, what happens if you try to convert a string of actual letters into an integer?
Boom! Python crashes with a new error:
ValueError: invalid literal for int() with base 10: 'twenty'
Python is telling you: "I understand how to convert the text '20' into the number 20, but I have no idea how to translate the word 'twenty' into digits."
Whenever you use int() or float() to convert user data, you must ensure the text actually contains numbers. As you build more advanced applications later, you will learn how to handle these errors gracefully so your program doesn't crash when a user makes a typo!
Type Conversion (Casting)
Type conversion (often called casting) is the process of actively changing a value from one data type into another using Python's built-in conversion functions:
str(): Converts any value into a String (text).int(): Converts a string or float into an Integer (whole number).float(): Converts a string or integer into a Float (decimal number).
Remember our crashing code from earlier where we tried to add a number to a string? We can fix it instantly by wrapping our integer inside str():
Converting Input Strings to Math Numbers
Type conversion is also essential when working with numbers that start out as text. For example, if a user types a number into a prompt, Python treats it as a string. If you want to do math with it, you must cast it:
Lesson Summary
You have mastered the art of inspecting and transforming data! Let's review the key takeaways:
type()function: Use this built-in tool anytime to check what data type a variable is holding.TypeError: The error Python throws when you try to combine incompatible data types (like gluing a number to a string without casting).- Casting Functions:
str()turns numbers or booleans into text.int()turns numeric strings or floats into whole integers.float()turns numeric strings or integers into decimals.
Being able to convert data types fluidly allows you to bridge the gap between user inputs, text displays, and mathematical calculations without crashing your programs.