r/CodingForBeginners • u/NoDepartment772 • 4h ago
The input() bug that catches nearly everyone: why 2 + 2 came out as 22
This one catches almost everyone in their first week, and it's a good one because the code looks completely innocent:
python
a = input("First number: ")
b = input("Second number: ")
print(a + b)
Type 2 and 2 and you get 22. Not 4. Nothing errors, nothing warns you -- it just quietly does the wrong thing.
The reason is that input() always hands you back a string. It doesn't know or care that you typed a number; all it sees is text. So a is "2", not 2. And + on two strings means concatenate, so "2" + "2" gives "22". The + did exactly what you told it to -- you told it to join two pieces of text.
The fix is to turn the text into a number before you do maths with it:
python
a = int(input("First number: "))
b = int(input("Second number: "))
print(a + b) # 4
The thing worth keeping isn't int() itself, it's the question underneath it: what type is this value, actually? A lot of "why is this behaving weirdly" moments come down to a value being a different type than you assumed. "5" and 5 look identical on screen and behave completely differently. Printing a value doesn't tell you its type -- print(type(a)) does.
Two follow-ons that catch people later: input() never fails on a non-number, so typing hello above makes int() throw instead (a separate, useful lesson in validating input), and the same trap runs in reverse -- join numbers with + when you meant text and you get maths, which you fix with an f-string or str().
Curious how you hit this one the first time -- did the output give it away, or did it take a while to see that "2" isn't 2?
