int() for whole numbers, float() for anything with a decimal point.
quantity = int("3") price = float("4.75") print(quantity * price)
14.25
Surrounding spaces and a trailing newline are fine, which helps with lines read from a file or typed by a user:
print(int(" 42\n") + 1)
43
What fails, and what to do about it
int() is strict. It refuses anything that isn't a plain whole number:
for text in ["3.5", "1,250", "£20", ""]: try: print(int(text)) except ValueError as e: print(e)
invalid literal for int() with base 10: '3.5' invalid literal for int() with base 10: '1,250' invalid literal for int() with base 10: '£20' invalid literal for int() with base 10: ''
Each has its own fix:
print(int(float("3.5"))) # 3: float first, then drop the decimals print(round(float("3.5"))) # 4: or round it print(int("1,250".replace(",", ""))) # 1250: remove thousands separators print(float("£20".lstrip("£"))) # 20.0: strip the currency symbol
3 4 1250 20.0
round() uses banker's rounding, so round(2.5) is 2, not 3: halves go to the even neighbour.
Numbers from a user
People type things you don't expect. Keep asking until the answer converts:
def ask_age(answers): for text in answers: # stands in for input() so this runs as-is try: return int(text) except ValueError: print(f"{text!r} isn't a whole number, try again") print(ask_age(["twenty", "20.5", "20"]))
'twenty' isn't a whole number, try again '20.5' isn't a whole number, try again 20
In a real program, the loop is while True: with text = input("Age: ").
And back again
str(14.25) turns a number into text. For joining text and numbers, an f-string does the conversion for you: f"Total: {total}". Writing "Total: " + total raises TypeError: can only concatenate str.
If the numbers are money, look at decimal.Decimal("4.75") instead of float: floats can't store most decimal fractions exactly, which is why 0.1 + 0.2 isn't 0.3.