Welcome to the next step in our journey with Python's basic building blocks. In our last lesson, we saw how operators like + behave differently with strings (concatenation) versus numbers (addition). We encountered a TypeError when we tried to join a string and a number directly, and we used the str() function as a quick fix.
Today, we're going to explore this concept of converting data from one type to another more formally. This process is known as type casting or type conversion. You will learn how to use Python's built-in functionsβint(), float(), and str()βto deliberately change the data type of a variable. Mastering this skill is essential, as it allows you to handle different kinds of data flexibly, especially when working with user input, which we'll cover soon.
What is Type Casting?
In Python, every value has a data type, and the type determines what you can do with it. You can't perform mathematical subtraction on a string, for instance. Type casting is the process of explicitly telling Python to convert a value from its current type to a new one.
Think of it like changing ingredients for a recipe. You can't mix whole oranges into a drink, but you can use a juicer to convert them into juice, which you can then mix with other liquids.

The three main "juicers" or casting functions you'll use are:
int(): Converts a value to an integer.float(): Converts a value to a floating-point number.str(): Converts a value to a string.
The following video from Bro Code provides a fast-paced and clear overview of how to use these functions.
Learn type casting in 7 minutes! π±
This video, "Learn type casting in 7 minutes! π±," is a great introduction that demonstrates explicit type conversion for integers, floats, and strings.
Watch these segments to see type casting in action: The introduction explains what type casting is and why it's useful. From integer to float: See how float() is used to convert an integer, adding a decimal part. From float to integer: Pay close attention to how int() handles a float. Notice that it truncates (cuts off) the decimal part, it does not round it. To a string: This section shows how str() converts a boolean to a string, reinforcing what you learned in the previous lesson.
A Closer Look at Casting Functions
Let's break down the rules for each function. The W3Schools page on Python Casting is an excellent, concise reference for this.
This resource provides clear examples for each of the core casting functions.
Read the entire section with examples for int(), float(), and str(). As you read, try to predict the output of each example before looking at the result.
As you saw, here are the key behaviors:
-
int():- When converting a float like
5.9, it cuts off the decimal to produce5. - When converting a string like
"10", it produces the integer10. - Important: Trying to convert a string that doesn't look like a whole number, such as
int("5.9")orint("hello"), will cause aValueError.
- When converting a float like
-
float():- Converts an integer like
10into10.0. - Converts a string like
"3.14"into the float3.14. It can also handle integer-like strings, sofloat("10")becomes10.0.
- Like
int(), it will raise aValueErrorif you give it a non-numeric string likefloat("banana").
- Converts an integer like
-
str():- This is the most flexible function. It can convert almost any data type into its string representation.
str(5.9)becomes"5.9"andstr(10)becomes"10".
- This is the most flexible function. It can convert almost any data type into its string representation.
This table provides a handy summary of the conversions we've discussed.

The Most Common Use Case: Handling User Input
So, why is this so critical? One of the most common situations where you'll need type casting is when you ask a user for input. In Python, the input() function always returns a string, even if the user types in numbers.
If you ask for a user's age and they type "25", Python sees it as the string "25", not the number 25. You can't do math with it until you convert it.
The following video from Khan Academy provides a perfect demonstration of this exact problem and its solution.
Type casting | Intro to CS - Python | Khan Academy
This video, "Type casting," clearly illustrates the problem of getting string data from the input() function when you need a number for calculations.
First, watch this segment to see the TypeError that occurs when you try to add a string from input() to a number. Next, see how the problem is solved by using int() and float() to cast the string input into a number before performing the calculation.
This example highlights the fundamental workflow: get input as a string, convert it to the necessary numeric type (int or float), perform your calculations, and if needed, convert the result back to a string (str) for display.
Practice Exercise: A Simple Price Calculator
Let's apply what you've learned. Open your code editor and create a new Python file. Your task is to calculate the total cost of an item including sales tax.
- Create a variable
item_price_strand assign it the string value"49.95". - Create a variable
tax_rate_floatand assign it the float value0.07. - Now, perform the following steps:
- Convert
item_price_strinto a floating-point number and store it in a new variable calleditem_price_float. - Calculate the tax amount by multiplying
item_price_floatbytax_rate_float. Store this in a variable calledtax_amount. - Calculate the total cost by adding
item_price_floatandtax_amount. Store this intotal_cost.
- Convert
- Finally, you need to print a user-friendly message. Create a
messagevariable by concatenating strings and thetotal_cost. Remember, you'll need to casttotal_costback to a string!- The message should look like:
"Total cost including tax: 53.4465"
- The message should look like:
- Use
print(message)to display the final output.
This exercise will guide you through a full cycle: converting a string to a number for a calculation, and then converting the numeric result back to a string for display.
Conclusion
In this lesson, we demystified the process of changing data types in Python. You now have a crucial tool for writing programs that can handle different kinds of data without crashing due to type errors.
Here are the key takeaways:
- Type casting is the explicit conversion of a value from one data type to another.
- The primary functions for this are
int(),float(), andstr(). int()truncates (chops off) decimals from floats.- Attempting to convert an incompatible string (like
"hello"toint) will result in aValueError. - Type casting is absolutely essential for processing numeric data received from the
input()function, which always provides a string.
In our next lesson, we will put everything from this module togetherβvariables, arithmetic operations, and type castingβto solve some simple but complete calculation problems.