-1

I am a C programmer with a decent knowledge of C++. I am learning python and was trying some stuff with the new syntax.

a=input("a: ")
b=input("b: ")

print("a+b=", 2*a + b)

Say I enter a=10 and b=20. Very strangely, this gives an output of 101020.

Why is this happening?

2 Answers2

4

The type for the return of input() is string. 2*string simply copies the string twice. Hence the two tens followed by twenty all concatenated together.

Cresht
  • 1,020
  • 2
  • 6
  • 15
2

What you can do is you can wrap the inputs around the built-in int() function. This is the same as static casting in C++, since you said you're familiar with it.

This would be the most effective way to achieve what you're aiming for:

a=int(input("a: "))
b=int(input("b: "))
print("a+b=", 2*a + b)

This way, it no longer concatenates the two strings together but adds the newly converted integers.

coddingtonjoel
  • 189
  • 2
  • 12