r/learnpython • • 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: 3
value of b: 5
8
35
<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'>
0 Upvotes

11 comments sorted by

View all comments

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)
"""