Solve typeerror not supported between instances of str and int (>, <, <=)

Problem

When comparing two numbers, typically using an IF statement in Python3, you get the following error:

typeerror <, > , <= not supported between instances of str and int

Let’s reproduce the error with a trivial example:

# define variables

sales = '111000'
costs = 55555

if sales > costs:
      print ('We are already profitable.')
else:
    print ("We still have lots of work until profitability.")

Running this example in your Python Integrated Development Environment (Jupyter, VS Code, Spyder, PyCharm) will return a type error as we are trying to compare between two variables that can’t be compared – in this case: string and integer.

Solution

As mentioned above, the root cause is that the variable instances of string and integer type are not compatible and hence can’t be compared.

We can easily convert the sales string to an integer type and go ahead with the comparison:

if int(sales) > costs:
    print ('We are already profitable.')
else:
    print ("Still lots to work until profitability")

Alternatively, we can convert to a float number and compare:

if float (sales) > costs:
    print ('We are already profitable.')
else:
    print ("Still lots to work until profitability")

This will return the following result:

We are already profitable.

Note: Although we used the > operator for comparison, all the above is completely relevant for the other comparison operators: <, =>, <= and ==.

Related learning