In this lesson, you will learn how to explicitly convert between numbers and strings so that Python can combine or process them correctly.
The Need for Conversion
In Python, you cannot directly "add" a string to an integer. If you try to combine a piece of text (like "I am ") with a number (like 25), Python will raise a TypeError because it doesn't know how to merge two different object types. To fix this, we must explicitly change the data type of the value to match the others.
Converting Numbers to Strings
When you want to display a number alongside text, you use the str() function. This function creates a new string object representing the number, allowing you to join it with other strings using the + operator.
age = 25
# This line works because 25 is converted to "25"
message = "I am " + str(age) + " years old."
print(message)
Converting Strings to Numbers
Conversely, if you receive numerical data stored as a string—perhaps from a user's input—you must convert it back into a number to perform math. You can use int() for whole numbers or float() for numbers with decimal points.
price_string = "10.99"
quantity = 2
# We must convert price_string to a float to perform multiplication
total = float(price_string) * quantity
print("Total cost is:", total)
Why it Matters
Python is a strongly typed language, which means it refuses to guess your intentions. If you have a variable x = "10" and y = 5, calculating x + y will fail. By using int(x) + y, you are taking control and telling Python exactly how to treat those objects. This step is essential whenever you move data from the "outside world" (which is usually text-based) into your program's logic (which is math-based), or vice versa.
Key Takeaway: Use str() to turn numbers into text for printing, and int() or float() to turn text into numbers for calculations.