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.

user3416724
  • 143
  • 2
  • 6

3 Answers3

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
vaultah
  • 44,105
  • 12
  • 114
  • 143
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.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
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))
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141