Course outline · 0% complete

0/27 lessons0%

Course overview →

Text vs numbers: converting input

lesson 2-3 · ~10 min · 7/27

The same symbols, different meanings

Everything typed into a program from outside — a web form, a chat box, this editor's Input box — arrives as text, even when it looks like a number. Mixing up "text that looks like a number" and an actual number is one of the most common real-world bugs (ages that will not add, prices that glue together instead of totaling), and this lesson is how you avoid it.

Here is a classic beginner surprise. What + does depends on what it is given:

print("5" + "5")
print(5 + 5)

The first line joins two strings (lesson 2-1) and outputs 55. The second adds two numbers (lesson 2-2) and outputs 10. Same operator, totally different results. This is why Python cares so much about the difference between "5" and 5. The kind of value something is (string, integer, float) is called its type.

Code exercise · python

Run it and confirm the two different behaviors of + for yourself.

input() always gives you a string

Remember input() from lesson 1-3? Whatever the user types arrives as a string, even if they typed digits. If you want to do math with it, convert it to an integer first with int(...):

print(int(input()) + 5)

Read inside-out, like in lesson 1-3:

  1. input() reads the typed line, say "10" (a string)
  2. int("10") converts it to the number 10
  3. 10 + 5 is 15, and print shows it

There is also float(...) for decimal input, and str(...) to go the other way, turning a number into a string.

Quiz

The user types 3 and the program runs print(input() + input()) with a second typed line of 4. Why is the output 34 instead of 7?

Code exercise · python

Your turn. The Input box contains the number 21. Write a program that reads it, converts it to an integer, and prints its double (should output 42).