Skip to Content
Course content

26: Type Conversion and Casting

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this all the time when I'm reviewing code for junior devs: the assumption that calling a conversion function like int() or str() actually "changes" the variable itself. It's a mental hurdle because, in some other languages, you can force a variable to change its nature. In Python, that's not how it works.

Casting isn't a permanent mutation

You might be tempted to write something like this, thinking you're converting a string to an integer so you can do math with it later:

age = "25"
int(age) 
print(type(age)) # You might expect <class 'int'>

If you run that, you'll see it still prints <class 'str'>. Why? Because strings and integers in Python are immutable. When you call int(age), Python isn't reaching inside the age variable and flipping a switch. Instead, it's creating a brand new integer object in memory and then... throwing it away immediately because you didn't tell Python where to put it.

Capturing the new type via assignment

To actually "cast" a value in a way that's useful, you have to assign the result of that conversion to a variable. I usually recommend either using a new variable name to keep things clear, or re-assigning it to the original name if you no longer need the old type.

# The right way to do it
price_str = "19.99"
price_float = float(price_str) 

# Now we can actually do math
total = price_float * 1.07 
print(total)

This is the core of type casting: you aren't transforming an object; you're creating a new object based on the value of the old one.

The 'float-to-int' conversion trap

Here is a nuance that trips up almost everyone eventually. Let's say you have a string that looks like a decimal, like "10.5", and you want it to be an integer. Your instinct is to do this:

value = "10.5"
number = int(value) # This will crash your program

Python will throw a ValueError. It's being strict here: int() can convert a string that looks like an integer, but it refuses to guess how to handle a decimal point inside a string. If you want that 10.5 to become 10, you have to go through a middleman. You cast the string to a float first, and then cast that float to an integer.

value = "10.5"
# String -> Float -> Int
number = int(float(value)) 
print(number) # Result: 10

I've spent way too many hours debugging "mysterious" crashes only to realize I was trying to cast a float-string directly to an int. Just remember: if there's a dot in the string, float() is your first stop.




📋 Practical Task

The Mixed-Type Invoice Total Calculator

You are building a small script to process an order. You receive the item price and the quantity as strings (simulating input from a web form), but you need to calculate the final total including a 5% tax.

Your task: Create a script that does the following:

  • Start with two variables: item_price = "45.50" and quantity = "3".
  • Convert these strings into the appropriate numeric types (float and int) to perform the calculation.
  • Calculate the subtotal (price times quantity).
  • Calculate the final total by adding a 5% tax (subtotal * 1.05).
  • Print a final message in this exact format: "The total cost is: [total]". Note: Since you cannot concatenate a string and a float, you must cast the final total back into a string for the print statement.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.