-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.

2
  • I suggest you read the official Python tutorial, it's quite good. Commented Dec 26, 2018 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... Commented Dec 26, 2018 at 17:06

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

5 Comments

"It can only handle strings". Really? What about lists,?
Oops, my mistake! Improved it, thanks for the warning!
Appreciate the edit but I think you've been too hasty :) now you're saying that + will not work with numbers. The fact is that the symbol will be interpreted differently based on types.
In a context in which you use strings, the + will work as a concatenate operator. But I see your point. Just give me a second to better put why Python will be in conflict.
Okay, fixed. Thanks very much for the advices and the patience :)
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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.