runtime
09 / 250
lesson 09 Variables & Data Types · beginner

Turn text into a number

A typed line is text, even when it looks like a number. int(), float(), and str() convert it.

You'll be able to
  • Turn text into a whole number with int()
  • Turn text into a decimal with float()
  • Turn a number into text with str()
The idea

"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.

example-1.py · Three conversions
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.

example-2.py · Text that is not a whole number
qty = int("12.5")
print(qty)
example-3.py · A typed number, tidied
boxes_text = input("Boxes? ")
boxes = int(boxes_text)
print(boxes_text)
print(boxes)
Review
  • 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.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Turn text into a number — Variables & Data Types · Runtime