Lessons · Python · text vs numbers
Text that looks like a number is still text
"5" and 5 are different things. Convert at the boundary with int() or float(), and never do arithmetic on the text.
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
Form fields, CSV cells, query strings, environment variables all arrive as text. '1' + '2' being '12' is the bug that follows.
How to think about it
Ask: where did this value come from? If from outside the program, convert it once as it enters, then treat it as a number everywhere else.
Worked example
age_text = input() # user typed 34Text, always.
age = int(age_text)Now a number.
print(age + 1)35. With the text version you would get an error, or '341'.
Your turn
Read a price from a CSV cell.
price = (cell)
Solve one with the tests running
The trap
int("3.5") fails; use float. And int(" 3 ") works, but int("3 apples") does not; validate before converting.
Practise text vs numbers on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.