By the end of this lesson, you will be able to convert data between integers, floats, and strings using Python's built-in casting functions.
What it is
Type casting (or type conversion) is the process of converting a variable from one data type to another. In Python, this is done explicitly using constructor functions like int(), float(), and str(). Unlike some languages that perform implicit conversions automatically, Python requires you to state your intent clearly to prevent unexpected behavior.
The mental model is simple: imagine each function as a translator. int() translates a number or numeric string into a whole number. float() translates it into a decimal number. str() translates almost anything into text.
Why it matters
- User Input Handling: The
input()function always returns a string. You must cast it tointorfloatto perform math. - Data Formatting: You often need to combine numbers with text in print statements, requiring
str(). - Precision Control: Converting a float to an int truncates decimals, which is useful for counting items where fractions don't make sense.
- API Interactions: JSON data often comes in as strings or specific types; casting ensures your variables match expected formats.
Syntax or steps
The syntax follows the pattern type(value). Here are the three most common casts:
int(x): Convertsxto an integer. Ifxis a float, it removes the decimal part (truncation). Ifxis a string, it must contain only digits (optionally with a sign).float(x): Convertsxto a floating-point number. It can handle integers, strings representing decimals, or scientific notation.str(x): Convertsxto a string representation. This works for almost any object.
Example
# Simulating user input which is always a string
user_age_str = "25"
user_height_str = "1.75"
# Casting string to integer for age
age = int(user_age_str)
# Casting string to float for height
height = float(user_height_str)
# Performing calculations
print(f"Age: {age}, Height: {height}")
# Casting back to string for concatenation
message = "User is " + str(age) + " years old."
print(message)
# Truncating a float to an int
pi = 3.99
whole_pi = int(pi)
print(f"Truncated Pi: {whole_pi}") # Output: 3
Explanation: First, we define two strings. We use int() on "25" to get the number 25. We use float() on "1.75" to get 1.75. Later, we cannot add a number directly to a string ("User is " + 25), so we wrap age in str(). Finally, int(3.99) becomes 3, not 4, because it truncates rather than rounds.
Common mistakes
- Casting non-numeric strings: Running
int("hello")raises aValueError. Always validate input or use try-except blocks. - Expecting rounding from int(): Developers often think
int(3.9)equals 4. It equals 3. Useround()if you need nearest-integer logic. - Losing precision: Converting a large float to an int might lose significant data. Be careful when casting financial data.
- Implicit assumptions: Remember that
input()never gives you an int. You must always cast it.
When to use it
Use explicit casting when you know the source type differs from the target type. Compare it with dynamic typing:
| Scenario | Action | Reason |
|---|---|---|
| Math operations on input | Cast to int/float |
Strings cannot do arithmetic. |
| Printing numbers with text | Cast to str |
Concatenation requires matching types. |
| Checking if value is numeric | Do NOT cast blindly | Use .isdigit() or try-except first. |
Practice
Guided Exercise: Write a script that asks the user for two numbers separated by a space (e.g., "10 20"). Split the string, cast both parts to integers, and print their sum.
Challenge: Take the float 9.8765. Cast it to an integer, then cast that result back to a float. What is the final output? Why did the decimal places disappear?
Hint: The intermediate step loses the fractional part permanently.
Quick check
Question: What is the result of int("10.5")?
Answer: It raises a ValueError. You cannot cast a string containing a decimal point directly to an integer. You must first cast to float, then to int: int(float("10.5")).
Summary
Type casting allows you to control how Python interprets data, bridging the gap between text-based inputs and numerical computations. Mastering int(), float(), and str() is essential for robust data handling and preventing runtime errors.