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

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.

-2

u/Winter-Drama2001 Nov 03 '24

ohhhhhhh understood πŸ™‡ thank you

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

u/Winter-Drama2001 Nov 03 '24

ohhhhhhh understood πŸ™‡ thank you

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

u/Winter-Drama2001 Nov 03 '24

ohhhhhhh understood πŸ™‡ thank you

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

u/JoeysSmallWood1949 Nov 03 '24

ohhhhhhh understood πŸ™‡ thank you

2

u/nath_ Nov 03 '24

Wrong account?

2

u/twizzjewink Nov 03 '24

You are concatenating strings, cast to int before math functions

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