Changing types: int(), float() and str()
🌍 In real life. At a money changer, you hand over 10 dollars and get back taka: the same money, in a different form you can spend here. Your original note isn't changed; you're given something new. And if you hand over a bus ticket, the changer can't turn it into taka at all.
Python's type conversions work the same way.
The idea in one sentence: int(), float() and str() build a new value of another type from the value you give them, if it can be read that way.
Its words:
- conversion: making a value of one type from a value of another
int(): makes a whole numberfloat(): makes a number with a decimal pointstr(): turns anything into text- ValueError: the error when the value can't be read as the type you asked for
Step by step, for int("42"):
int()reads the characters4and2.- They're all digits, so it builds the whole number 42.
- It gives back 42, an
int. The string"42"is unchanged.
text = "42"
number = int(text)
print(number + 1)
print(type(number))float() reads decimals. And int() of a float cuts off the decimal part. It doesn't round: int(3.99) is 3.
print(float("3.5"))
print(float("7"))
print(int(3.99))str() is how you join a number into text with +:
age = 12
print("I am " + str(age) + " years old")How Python reads text as a number. int() accepts digits with an optional - or + sign in front, and ignores spaces at the two ends: int(" 42 ") is 42. It even reads Bangla digits: int("১২") is 12. But anything else inside, a space between digits, a decimal point, a comma, a letter, makes it give up.
float() is a little more relaxed: it reads decimal points, and even "1e3" (1 × 10³, which is 1000.0).
int() of a float cuts off the decimal part, toward zero: int(-3.9) is -3. Use round() if you want the nearest whole number.
Not everything can be converted. Text that doesn't look like a number gives a ValueError:
print(int("abc"))print(int("3.5"))Mistakes and edge cases.
- A decimal point for int().
int("3.5")givesValueError: invalid literal for int() with base 10: '3.5'. Usefloat(). - An empty answer.
int("")givesValueError: invalid literal for int() with base 10: ''. This happens when the user just presses Enter. - Expecting rounding.
int(3.99)is 3, not 4. - Converting without keeping it.
int(text)alone makes a number and throws it away;textis still a string. Writenumber = int(text).
Quiz
What does this print?
print(int("8") + 2)And this one?
print("8" + "2")What does this print?
print(int(9.7))What does this print?
print(float("2"))What does
int("hello")do?- Stops with a ValueError
- Gives 0
- Gives "hello"
Which line causes an error?
price = 30 print("Total: " + price)
Coding tasks
textholds"25". Makenumberhold it as an int, then makedoubleholdnumbertimes 2.aholds"3.5"andbholds"1.5"(both are text). Print their sum as a number:5.0.scoreis 90. PrintScore: 90by joining text with+andstr()(no f-string this time).