How To Solve The “TypeError: > not supported between instances of float and str”

This article will introduce how to fix the “TypeError: > not supported between instances of float and str” error. All programmers encounter this common mistake when comparing two different value types. We tested it effectively by ensuring the two values were the same type of float using the float() method to force the type of value. Please read the article for more details.

The cause of this error

The error “TypeError: > not supported between instances of float and str” in Python occurs when you compare two values with the typed string and float with the other by using '>'.Python will show you an error when you try to do that.

Example:

In this example, we use the if else condition to compare two values Maths type is float, and the Literature type is a string. Two values are not the same type, so the error will be shown when we try to run this code.

# Creating values 
maths = 9.5 # float type
literature = '7.0' # string type

# This is the cause of this error. Compare two values that are not the same type
if maths > literature:
    print("Maths scores higher than Literature")
else:
    print("Literature scores higher than Maths")

Output

The error will show if you try to run this code.

TypeError: '>' not supported between instances of 'float' and 'str'

To Deal with the “TypeError: ‘>’ not supported between instances of ‘float’ and ‘str’” error

The error “TypeError: ‘>’ not supported between instances of ‘float’ and ‘str'” will be solved by ensuring the type of the two variables you used to compare is the same. In the example above, we make a comparison between two values, and one is the string type, and one value is the float type, and it shows you an error. You can use the float() method in the second value to force the type of it into the float, comparing two values together.

Convert string to float type using float() method.

For the type of variable in the string, you can use the float() method to convert it into a float. The float() method returns a floating-point number for a provided number or string. Let’s see the example below.

# Creating values 
maths = 9.5 # float type
literature = '7.5' # string type

# Using the float() method to convert string into float
if maths > float(literature):
    print("Maths scores higher than Literature")
else:
    print("Literature scores higher than Maths")

Output

Maths scores higher than Literature

Summary

To sum up, the error “TypeError > not supported between instances of float and str” in Python occurs when you compare different value types between float and string types. It would be best if you first converted the value on a float using the float() method and then compared them. Don’t hesitate to comment below if you have any questions.

Thank you for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *