-4

I want to make a simple addition program but get stuck at an error stating the following: TypeError: can only concatenate str (not 'int') to str.

I have no idea what to do, I am pretty new to Python coding.

def addition():
    x = int(input("Please enter the first number:"))
    y = int(input("Please enter the second number:"))
    z = x+y
    print("The sum of " +x+ " and " +y+ " gives " +z )

I expect the code to return the value of the sum of the two entered values.

Sumedh
  • 89
  • 1
  • 2
  • 8
  • I suggest you read the [official Python tutorial](https://docs.python.org/3/tutorial/), it's quite good. – mkrieger1 Dec 26 '18 at 16:29
  • Thanks a lot, to everybody that helped, I know it was a silly question, but still I am quite new in Python coding. Thanks a lot again... – Sumedh Dec 26 '18 at 17:06

2 Answers2

2

The + operator can work in multiple contexts. In this case, the relevant use cases are:

  • When concatenating stuff (strings, for example);

  • When you want to add numbers (int, float and so on).

So when you use the + in a concept that uses both strings and int variables (x, y and z), Python won't handle your intention correctly. In your case, in which you want to concatenate numbers in the sentence as if they were words, you'd have to convert your numbers from int format to string format. Here, see below:

def addition():
    x = int(input("Please enter the first number:"))
    y = int(input("Please enter the second number:"))
    z = x+y
    print("The sum of " + str(x) + " and " + str(y) + " gives " + str(z))
Pedro Martins de Souza
  • 1,406
  • 1
  • 13
  • 35
1

The problem is when you print the output (print("The sum of " +x+ " and " +y+ " gives " +z )), you are adding strings to integers (x, y, and z).

Try replace it with

print("The sum of {0} and {1} gives {2}".format(x, y, z))
Xiaoyu Lu
  • 3,280
  • 1
  • 22
  • 34