Turn text into a number
A typed line is text, even when it looks like a number. int(), float(), and str() convert it.
- Turn text into a whole number with int()
- Turn text into a decimal with float()
- Turn a number into text with str()
"12" and 12 both print as 12. They are not the same kind of value. "12" is text. int("12") reads that text as a whole number. float("12.5") reads text as a decimal. str(12) goes the other way: a number becomes text.
input() always gives you text. A typed price is text until you convert it. Converting also tidies what people type: int("007") is 7, and int(" 5 ") is 5, because spaces around the digits are allowed.
Run each example to see what it prints. Running examples doesn't count toward progress.
qty = int("12") price = float("12.5") label = str(12) print(qty) print(price) print(label)
int() only accepts text that is a whole number. int("12.5") stops the program. A decimal in text needs float().
int() of a decimal value (not text) is allowed: it keeps the whole part and drops the rest, so int(12.9) is 12 and int(-2.5) is -2. It never rounds up.
qty = int("12.5") print(qty)
boxes_text = input("Boxes? ") boxes = int(boxes_text) print(boxes_text) print(boxes)
- int() turns whole-number text into a whole number. float() turns decimal text into a decimal.
- int() of a decimal value keeps the whole part. str() turns a number into text.
- int("12.5") is an error. A typed line from input() is text until you convert it. Next: None, and asking for a value's kind.