Level 1
0 / 100 XP

When types collide

Python refuses. You can't glue a string and an integer together directly — they're different types and Python won't guess what you meant.

Why Python is strict about this

Consider what "adding" a string and a number could mean:

Python
"10" + 5 # Did you mean 15? Or "105"?

Python doesn't know. Rather than guess wrong and silently produce bad output, it stops and tells you there's a problem. That's a feature, not a bug.

The fix: str()

Convert the number to a string first, then concatenate:

Python
name = "Alice" age = 25 print(name + " is " + str(age) + " years old") # Alice is 25 years old

str() turns any value into its string equivalent. The number 25 becomes the text "25", and now Python can glue it together with the rest.

The other direction: int() and float()

You can also go the other way — convert a string into a number:

Python
price_text = "9" price_number = int(price_text) print(price_number + 1) # 10

And for decimals:

Python
temperature_text = "36.6" temperature_number = float(temperature_text) print(temperature_number + 1) # 37.6

What happens when the conversion fails

If the string doesn't look like a number, Python raises an error:

Python
int("hello") # ValueError: invalid literal for int()

You can only convert strings that actually contain valid numbers. "25" works. "twenty-five" does not.

Key takeaways

  • Python will not mix strings and numbers automatically — you have to convert explicitly
  • str() turns a number into a string so you can concatenate it
  • int() and float() turn strings into numbers so you can do math
  • If the string doesn't contain a valid number, the conversion will fail with a ValueError