Beginner · 10 min
Converting numbers
Convert numeric text before doing arithmetic.
Turn numeric text into a number
int() converts whole-number text into an integer. Without conversion, adding two strings joins their text instead of adding numbers.
text = "12"
print(text + "3")
print(int(text) + 3)Output
123 15
Use decimal numbers
float() converts numeric text with a decimal point. / performs division and produces a floating-point result. Invalid numeric text cannot be converted this way.
price = float("2.5")
print(price * 2)
print(9 / 2)Output
5.0 4.5
Converting numbers
- Identify which values are strings and which are numbers.
- Convert numeric text before calculating with it.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Add a delivery fee
Convert amount_text to an integer. Add a delivery fee of 2, save the result in total, and display it.
Use int(amount_text) before adding the fee.