TypeError: ‘<' not supported between instances of 'str' and 'int' – How To Fix It?

not supported between instances of ‘str’ and ‘int’

With the “TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’” error you are getting, you can use the int() method to fix it. Follow this article for details on how to fix it.

What is the cause of TypeError: ‘< ‘not supported between instances of ‘str’ and ‘int’?

Only objects with the same numerical data type can be compared in Python using mathematical operators. If you employ a comparison operator, such as the more significant than the operator or >, you will cause this error.

Example:

You will get this problem because a string can’t compare to an integer. Look at the example below and determine if the input number is smaller than 18.

Code:

# Input age
age = input("Enter your age: ")

if age < 18:
	print("You must be over 18 to enter")
else:
	print("Welcome to our website")

Input:

Enter your age: 17

Output:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    if age < 18:
TypeError: '<' not supported between instances of 'str' and 'int'

As you can see, we can’t compare “age” with 18. The output will show you the error message: “TypeError:'<‘ not supported between instances of ‘str’ and ‘int'” because the input() method returns a string. This means our code tries to compare a string (the value in “age”) to an integer.

Solutions to fix this error

We should change the type of the input by function int(). After we wrap the string with int() method, the “age” type becomes an integer so we can compare it with another integer belike 18. You can use some Python functions like str() and float() to get the familiar result.

Code:

# Input age
age = int(input("Enter your age: "))

if age < 18:
 	print("You must be over 18 to enter")
else:
  	print("Welcome to our website")

Input:

Enter your age: 17

Output:

You must be over 18 to enter

So we can compare age with 18 now after we wrap the input() inside the int().

Summary

To summarize, the error TypeError:'<‘ not supported between the instance of ‘str’ and ‘int’ will occurs when you use any comparison operator to compare a string to an integer. The best way to solve this problem is to convert the string values into the same type value by built-in functions like float(), int().

Maybe you are interested in similar errors:

Leave a Reply

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