Can't convert 'int' object to str implicitly: Python 3+

14,240

Solution 1

As others have suggested, this comes from your call to input. In Python27:

>>> input() + 1
3 # I entered that
4

But using raw_input() (which has the same behaviour as input in Python3+):

>>> raw_input() + 1
3 # I entered that
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

And indeed, we have:

>>> x = raw_input()
3
>>> type(x)
<type 'str'>

In your code, your user-input x is a string, and the code complains on the line distinct(x+1) when you try to add a string and an int. Convert it first like this:

>>> x = int(input())
...

Solution 2

In order to concatenate strings and string representations of various types, you have to cast the latter to strings explicitly, e. g.

"(" + str(leftchild) + ", " + str(rightchild) + ")"

or, more readably,

"(%i, %i)" % (leftchild, rightchild)
Share:
14,240
user2860003
Author by

user2860003

Updated on June 05, 2022

Comments

  • user2860003
    user2860003 almost 2 years

    My code is supposed to determine and display the number of binary trees after an input.
    I keep getting the can't convert int object to str implicitly error and I have no idea how to fix it. It easily works in versions of Python under 3.0, so please help, as I'm still a beginner in Python and I would like to understand what I'm doing wrong.

    import sys
    print ("Welcome to Binary Tree Enumeration!")
    x = input("Type an integer to output its binary trees: ")
    print ("\nYou entered " + str(x))
    def distinct(x):
         leafnode = '.'
         dp = []
         newset = set()
         newset.add(leafnode)
         dp.append(newset)
         for i in range(1,x):
             newset = set()
             for j in range(i):
                 for leftchild in dp[j]:
                     for rightchild in dp[i-j-1]:
                         newset.add(("(") + leftchild + rightchild + (")"))
             dp.append(newset)
         return dp[-1]
     alltrees = distinct(x+1)
     for tree in alltrees:
         print (tree)
     print ("Thank you for trying this out!")
    

    I forgot to add...this is the error I'm getting.

    Traceback (most recent call last):
      File "main.py", line 29, in 
        alltrees = distinct(x+1)
    TypeError: Can't convert 'int' object to str implicitly