Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 10

Type Casting with `int()`, `float()`, and `str()`

Recommended resources

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.

This image compares type conversion in Python to making juice. Just as a juicer turns an orange into juice, the `int()` function can turn the string `"123"` into the integer `123`.

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.

Python Casting

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 produce 5.
    • When converting a string like "10", it produces the integer 10.
    • Important: Trying to convert a string that doesn't look like a whole number, such as int("5.9") or int("hello"), will cause a ValueError.
  • float():

    • Converts an integer like 10 into 10.0.
    • Converts a string like "3.14" into the float 3.14. It can also handle integer-like strings, so float("10") becomes 10.0.
    • Like int(), it will raise a ValueError if you give it a non-numeric string like float("banana").
  • str():

    • This is the most flexible function. It can convert almost any data type into its string representation. str(5.9) becomes "5.9" and str(10) becomes "10".

This table provides a handy summary of the conversions we've discussed.

This table shows common examples of converting between `int`, `float`, `str`, and `bool` data types using Python's casting functions.

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.

  1. Create a variable item_price_str and assign it the string value "49.95".
  2. Create a variable tax_rate_float and assign it the float value 0.07.
  3. Now, perform the following steps:
    • Convert item_price_str into a floating-point number and store it in a new variable called item_price_float.
    • Calculate the tax amount by multiplying item_price_float by tax_rate_float. Store this in a variable called tax_amount.
    • Calculate the total cost by adding item_price_float and tax_amount. Store this in total_cost.
  4. Finally, you need to print a user-friendly message. Create a message variable by concatenating strings and the total_cost. Remember, you'll need to cast total_cost back to a string!
    • The message should look like: "Total cost including tax: 53.4465"
  5. 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(), and str().
  • int() truncates (chops off) decimals from floats.
  • Attempting to convert an incompatible string (like "hello" to int) will result in a ValueError.
  • 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.