2


I'm slightly puzzled on this problem that I have with my Python program. It's a very simple program but it keeps coming up with a problem. Allow me to show you the code...

x=int(input('Enter number 1:'))
y=int(input('Enter number 2:'))
z=x+y
print('Adding your numbers together gives:'+z)

Now, this program, when I run it keeps on saying that "TypeError: Can't convert 'int' object to str implicitly".

I just want it to run normally. Could anyone help?
Thanks.

3
  • Look at your input lines and spot the obvious difference... Commented Mar 13, 2014 at 18:00
  • @TomFenech That's not a good duplicate. The title is similar but the question is rather different. Commented Mar 13, 2014 at 18:03
  • @JohnKugelman I take your point. Commented Mar 13, 2014 at 18:23

3 Answers 3

4

The problem is obvious because you can't concatenate str and int. Better approach: you can separate string and the rest of print's arguments with commas:

>>> x, y = 51, 49
>>> z = x + y
>>> print('Adding your numbers together gives:', z)
Adding your numbers together gives: 100
>>> print('x is', x, 'and y is', y)
x is 51 and y is 49

print function will take care of the variable type automatically. The following also works fine:

>>> print('Adding your numbers together gives:'+str(z))
Adding your numbers together gives:100
>>> print('Adding your numbers together gives: {}'.format(z))
Adding your numbers together gives: 100
>>> print('Adding your numbers together gives: %d' % z)
Adding your numbers together gives: 100
Sign up to request clarification or add additional context in comments.

Comments

3

You should rewrite the last line as:

print('Adding your numbers together gives:%s' % z)

because you cannot use + sign to concatenate a string and an int in Python.

Comments

3

Your error message is telling you exactly what is going on.

z is an int and you're trying to concatenate it with a string. Before concatenating it, you must first convert it to a string. You can do this using the str() function:

print('Adding your numbers together gives:' + str(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.