Hone

Lessons · Python · text that should be a number

Text that should have been a number

int('10') reads a string of digits and gives the number 10, so you can do maths on what a person typed.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Everything typed into a box, read from a file or pulled from a URL arrives as text. '10' + '5' is '105'. int() is the step between reading input and using it.

How to think about it

Trace where the value came from. If it came from a keyboard, a file or the web, it is text until you convert it, however numeric it looks.

Worked example

raw = "10"
Text, two characters.
print(raw + "5")
105: text joins, it does not add.
n = int(raw)
Now the number ten.
print(n + 5)
15.
print(int("  7 "))
7: surrounding spaces are fine.

Your turn

Read the typed age as a number.

age = (typed)

The trap

int('3.5') raises ValueError; int(3.5) gives 3. Parsing text and truncating a float are different jobs that happen to share a name.

Practise text that should be a number on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.