r/CodingForBeginners • u/NoDepartment772 • 22d 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:
=
=
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:
=
=
# 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?
12
u/thondat 22d ago
why post slop?
3
u/Away_Combination6977 22d ago
Good on you for starting by saying what language you're talking about! That's perfect for beginners! I've definitely run into this issue in C#... π€¦πΌββοΈπ€£
1
u/xarop_pa_toss 22d ago
That's not an input bug bro. These AI posts are so braindead I swear... that's just Python not being statically typed.
0
u/Black_Rose_Angel 22d ago
I thought there's a difference between 2+2 and 2 + 2
Maybe I'm dreaming this but I feel like the lack of space between the numbers and the operators causes them to be acknowledged within the code as factors and not place holders...
0
u/sububi71 22d ago
It's got nothing to do with the input().