r/learnpython • u/Winter-Drama2001 • Nov 03 '24
how is 3+5 38? [input function]
SOLVED
this is the code:
a=input("value of a: ")b=input("value of b: ")print(3+5)print(a+b)print(type(a))
its output:
value of a: 3value of b: 5835<class 'str'>
I know the default datatype for input function is string, so i thought it would give an error. But the output is somehow 35? Can someone explain whats going on?
another eg:-
input:
a=input("value of a: ")
b=input("value of b: ")
print(4+6)
print(a+b)
print(type(a))output:
value of a: 4
value of b: 6
10
46
<class 'str'>8
u/eleqtriq Nov 03 '24
The input() function in Python returns a string, so when you use a=input("value of a: ") and b=input("value of b: "), both a and b are strings. When you use print(a+b), you're concatenating these two strings, not adding them as numbers. That's why you're seeing 35 and 46 instead of 8 and 10.
-4
3
u/CaptainCheezelz Nov 03 '24
βAddingβ strings using β+β concatenates them, for example: βFooβ + βBarβ == βFooBarβ
You need to cast your βaβ and βbβ to integers first.
-4
9
u/r-mf Nov 03 '24
a = int(input("value of a: "))
I swear if you give me another one of your copy pasted responses...Β
8
2
2
u/JonJonThePurogurama Nov 03 '24
okay we knew that the input function in Python will return the user input in string.
that is why when your program prompts you for input like 3 and 5 it will return a result of 35 because 3 and 5 is string returned by the input function and plus(+) operator in string will concatenate it. It joins or combine two string together as one. Like the example "hello" and "world", will be "helloworld".
It will not throw and error since both 3 and 5 are string and it can use plus(+) operator, but it will not add them like in numbers.
error will only shown if 3 and 4 are in different types like 3 is string and 4 is int.
if we visualize
"""
>>> "3" + "4"
"34"
>>> "3" + 4
TypeError can only concatenate str and (not int and str)
"""
25
u/[deleted] Nov 03 '24
The
+operator has different implementations for different types. For numbers it adds. For strings it concatenates. For others it might do something else, or you might add your own implementation.