-3

I have the following python code.

a = input("Enter first number") # 2
b = input("Enter second number") # 3

c = a+b # 23 instead of 5
print(c) # prints out 23 why?

I am using the following command to run python:

python3.7 filename.py 

Instead of adding two numbers is concatenates two numbers and give me 23 instead of 5 even though I am using python3.7.

Every answer that I read says it evaluates and return the correct type:

https://www.quora.com/What-is-the-difference-between-raw_input-and-input-in-Python#

john doe
  • 9,220
  • 23
  • 91
  • 167
  • `input()` always returns a string by default. The fact you're using 3.7 is inconsequential. – roganjosh Sep 17 '18 at 19:06
  • `input()` returns strings, not integers. Try it with `red` and `rum`. Convert the strings to integers using `int(...)` around the `input()` call. – kindall Sep 17 '18 at 19:06
  • Thanks! Looks like there are lots of articles on the web incorrect because they are suggesting that input evaluates and returns the correct type. – john doe Sep 17 '18 at 19:07
  • 1
    @johndoe `input()` in Python 2 calls `eval()` on the input. That's a terrible idea so it was dropped. No article on Python 3 would be correct if it suggests that's still the case - it's always a string. – roganjosh Sep 17 '18 at 19:08

1 Answers1

1

a+b concatenating string as input returns string. You need explicit type conversion to convert the input to integer using int() function.

a = int(input("Enter first number")) 
b = int(input("Enter second number"))
haccks
  • 104,019
  • 25
  • 176
  • 264