Back to Python Notes
Topic #214

Type Casting

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 to int or float to 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:

  1. int(x): Converts x to an integer. If x is a float, it removes the decimal part (truncation). If x is a string, it must contain only digits (optionally with a sign).
  2. float(x): Converts x to a floating-point number. It can handle integers, strings representing decimals, or scientific notation.
  3. str(x): Converts x to 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 a ValueError. Always validate input or use try-except blocks.
  • Expecting rounding from int(): Developers often think int(3.9) equals 4. It equals 3. Use round() 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.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Type Casting – FAQs

Quick answers about learning Type Casting in Python.

This free note from Coding Now Tech Institute explains Type Casting in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Type Casting, is 100% free with no signup required.
With focused practice, most students grasp Type Casting in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now