Python Type Casting: How to Convert Data Types

What Is Type Casting?

Type casting is the process of converting a variable from one data type to another. It helps you perform operations that wouldn't work with the original data type. This helps you avoid errors and ensures your code behaves as expected.

For example, you can't add a number and a string together. First, you must convert the string to a number.

Building a Career in Python? Master the foundation, like basics of variables, functions, and data types, Type Casting in our comprehensive free course.

Explore the free Python course →

How to Convert Data Types in Python

Python has simple, built-in functions for type casting. The three most common are int(), float(), and str(). Each function takes a value and converts it to the specified type.

1. Converting to an Integer with int()

The int() function converts a value into an integer, which is a whole number. You can give it a float or a string, and it returns a whole number.

Converting Float to Integers

When you convert a float to an integer, the int() function truncates the value. This means it cuts off the decimal part completely without rounding the number.

float_value = 15.75 integer_value = int(float_value) print("Original:", float_value) print("Converted:", integer_value)
float_value = 15.75
integer_value = int(float_value)
print(integer_value)
Your output will appear here...

Converting Strings to Integers

You can also convert a string to an integer, but only if the string contains a whole number. If the string has any non-numeric characters, Python raises a ValueError.

numeric_string = "250" # Convert string to int to perform math converted_integer = int(numeric_string) print(converted_integer * 2)
numeric_string = "250"
converted_integer = int(numeric_string)
print(converted_integer * 2)
Your output will appear here...

2. Converting to a Float with float()

The float() function converts a value into a floating-point number (a number with decimals). Use this when you need decimal precision in calculations. It works with integers and compatible strings.

Converting Integers to Floats

When you convert an integer to a float, the function adds a decimal point and a zero (.0) to the end.

my_integer = 42 my_float = float(my_integer) print(my_float)
my_integer = 42
my_float = float(my_integer)
print(my_float)
Your output will appear here...

Converting Strings to Floats

If you convert a string, it must represent a valid number. This can be either an integer or a float.

pi_string = "3.14159" pi_float = float(pi_string) print(pi_float)
pi_string = "3.14159"
pi_float = float(pi_string)
print(pi_float)
Your output will appear here...

You are making progress! Ready to test your skills with more complex challenges?

Try Python Exercises

3. Converting to a String with str()

You can convert almost any Python object into a string with the str() function. This works best when you want to combine numbers with text for display. For example, str(10.5) returns the string "10.5".

Why You Need str()

You often need str() when you want to print a message that includes a number. Python can't directly add a string and a number together, so you must first convert the number to a string.

user_age = 30 # This works correctly print("The user's age is: " + str(user_age))
user_age = 30
print("The user's age is: " + str(user_age))
Your output will appear here...

Common Use Cases for Type Casting

You'll use type casting in several common situations:

  • Process user input: The input() function always returns a string, so you need to convert it to work with numbers.
  • Perform mathematical calculations: When you get data from files or APIs, you often need to convert it before doing math.
  • Format output messages: You combine text with numbers, booleans, or other data types for display.

Potential Errors to Avoid

The most common issue you'll encounter with type casting is the ValueError. This error happens when you pass an incompatible value to a conversion function. For example, int("hello") fails because Python can't interpret "hello" as a whole number.

You should validate data before you try to cast it. This matters especially when you work with user input, since users may enter data in unexpected formats. You can use methods like str.isdigit() or a try-except block to handle conversion errors smoothly.

Example:

invalid_input = "hello" print(int(invalid_input))
#This will work, as input is whole number
valid_input = "123"
print(int(valid_input))
Your output will appear here...

Final Challenge: The Bill Calculator

Put your skills to the test! You have a price as a string and a tax rate as a float.

Your Task:

  1. Convert the price string to a float.
  2. Calculate the total cost (price + tax).
  3. Convert the total back to a string to print a final message.
item_price = "50.00" tax_amount = 4.50 # TODO: Convert item_price to float # price_float = ... # TODO: Calculate total # total = ... # TODO: Convert total to string and print message # print("Total is: " + ...)
item_price = "50.00"
tax_amount = 4.50

price_float = float(item_price)
total = price_float + tax_amount

print("Total is: " + str(total))
Your output will appear here...
🏆

Lesson Completed

You have successfully learned about Python Type Casting, including int(), float(), str(), and how to avoid ValueErrors.

📘

Full Python Course

Master Python with 11+ hours of content, 50+ exercises, and real-world projects.

Enroll Now
📝

Next Lesson

Continue with the next lesson on Python User Input.

Next Lesson ->

Scroll to Top