In Python, we have the
>
greater than operator, which is one of the 6 comparison operators. The Greater than operator operates between two operands and checks if the operand on the left is greater than the operand on the right.
The greater-than operator can only compare two values if they have a similar data type. If we put the Greater than operator between a string value and an integer value, we will receive the error »
TypeError: '>' not supported between instances of 'str' and 'int'
«.
In this Python tutorial, we will discuss this error in detail and learn how to fix it. We will also walk through some examples that demonstrate this error in a Python program, so you can get an idea of how to solve this error. So let’s get started with the error statement.
Python comparison operators can only compare some data values of similar data types. The Greater than operator is no exception, when trying to compare a string value with an integer value to find out which is greater we will encounter the TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’ Error. The Error Statement » TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’ » has two parts separated with a colon.
- TypeError
- ‘>’ not supported between instances of ‘str’ and ‘int’
1. TypeError
TypeError is an Exception Type. It is raised in a Python program when we perform an unsupported operation or function on an inappropriate data type. Performing the Grater than > comparison operation between a string and integer raises the TypeError.
2. ‘>’ not supported between instances of ‘str’ and ‘int’
The » ‘>’ not supported between instances of ‘str’ and ‘int'» statement is the error message that tag along with the TypeError message. This error message is telling us that Python does not support the > operation between a
str
and
int
instances. str and int are the default type for string and integer data types, respectively.
Error Example
Let’s say we have two numbers one is an integer, and the other is a string, and we want to find out which one is greater using the greater than operator.
# string number
x = '20'
# integer number
y = 30
if x > y:
print("x is greater than y")
else:
print('y is greater than x')
Output
Traceback (most recent call last):
File "main.py", line 6, in
if x > y:
TypeError: '>' not supported between instances of 'str' and 'int'
Break the code
In the above example,
x
is a numeric string value and
y
is an integer numeric value. And in line 6, when we are comparing both the value as
x > y
python could not compare them because it does not compare two different data type values.
Solution
Whenever we are comparing two data values, we need to ensure that both values have a similar data type. In the above example, we want to compare two numbers, x and y, so before comparing them, we need to convert the string value to int or float using the int() or float() functions.
# string number
a = '20'
# integer number
b = 30
# convert string into int
a= int(a)
if a > b:
print("a is greater than b")
else:
print('b is greater than a')
Output
b is greater than a
Common Example Scenario
This is not the only case when you encounter this error, there are some inbuilt Python methods such as
sort()
,
min()
,
max()
, etc., that also use
>
greater than or
<
less than operator to compare values. And they also throw the same error when we want to sort, and find out the maximum number from a list of integers that also contain some string value.
Example
Let’s say we have a list
prices
that contain the prices for different products, and we need to create
a program
that can find out the most expensive product price from the
prices
list.
# list
prices = [299, 449, 699, 899, '999']
expensive = max(prices)
print("Most expensive product price: ", expensive)
Output
Traceback (most recent call last):
File "main.py", line 4, in
expensive = max(prices)
TypeError: '>' not supported between instances of 'str' and 'int'
Break the code
In the above example, the
prices
list contains 5 price values, among which the last price value
'999'
is a string, and the rest of them are integers. And when we apply the
max()
function on the
prices
list to find out the most expensive price, we receive the error
TypeError: '>' not supported between instances of 'str' and 'int'
.
This is because, behind the scene, to compare the values, the
max()
function also use the Greater Than
>
operator to find out the greatest element. And when it tried to compare the
'999'
string value with the other integer number, it raised the error.
Solution
Whenever we use such functions and methods that use a comparison operator behind the scene, we should ensure that the values we are passing must have a similar data type. As far as our above example is concerned, we can convert all the
prices
list elements to the int using the map() and int function, then call the max() function on it.
# list
prices = [299, 449, 699, 899, '999']
# convert all elements to integer
prices = list(map(int, prices))
expensive = max(prices)
print("Most expensive product price:", expensive)
Output
Most expensive product price: 999
Conclusion
The »
TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’
» error is a very common error. The main reason why this error occurs in a Python program is when we try to compare a string value with an integer value. As many inbuilt Python functions and methods also use comparison operators to compare values, and when they receive values of different data types, they also return the same error.
If you are receiving this error in your Python program, it is not necessary that you are using the > operator between a string and int value. It may also be possible that you are passing a list or tuple that has integer as well as string values to the max(), sort(), and min methods.
Still, if you are getting this error in your Python program, you can share your code and query in the comment section. We will try to help you in debugging.
People are also reading:
-
Python String count() with Examples
-
Remove Last Character from Python String
-
Python String find() Method with Examples
-
String to int in Python
-
Python String Format
-
Check if a Python String Contains Another String
-
Python Int to string Tutorial
-
Python Compare Strings
-
Substring a String in Python
-
Reverse a String in Python
In Python, we can only compare objects using mathematical operators if they are the same numerical data type. Suppose you use a comparison operator like the greater than the operator or >, between a string and an integer. In that case, you will raise the TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’. This article will go through the error in detail, an example, and how to solve it.
TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’
Python is a statically typed programming language, which means you have to change the type of a value before comparing it to a value of a different type. In the case of a string and an integer, you have to convert the string to an integer before using mathematical operators. This particular TypeError is not limited to the “greater than” comparison and can happen with any comparison operator, for example, less than (<), less than or equal to (<=) or greater than or equal to (>=).
Example: Using the input() Function to Compare Numbers
You will typically encounter this error when using the input() function because it will return a string. Let’s look at an example of a program that takes an input and then tries to find the most significant number out of a collection of numbers, including the input.
# Input number
number = input("Enter a number to compare: ")
# Print output
print(f'The maximum number is {max(2, 4, 5)}')
print(f'The maximum number is {max(2, number, 5)}')
Enter a number to compare: 20
The maximum number is 5
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
print(f'The maximum number is {max(2, number, 5)}')
TypeError: '>' not supported between instances of 'str' and 'int'
In the first part of the code, we pass three integers to the max function, which will find the maximum number, 5. However, in the second part of the code, we give a string to the max function with two other integers, we raise the TypeError:’>’ not supported between instances of ‘str’ and ‘int’. The error occurs when we compare two values whose data types are different, a string and an integer.
Generally, we raise a TypeError whenever we try to do an illegal operation for a particular object type. Another typical example is TypeError: ‘int’ object is not subscriptable, which occurs when accessing an integer like a list.
Solution
Instead of passing a string to the max function, we can wrap the input() function in the int() function to convert the value to an integer. The process is of converting a literal of one type is called type casting or explicit type conversion. We can use Python inbuilt functions like int(), float() and str() for typecasting.
# Input number
number = int(input("Enter a number to compare: "))
# Print output
print(f'The maximum number is {max(2, 4, 5)}')
print(f'The maximum number is {max(2, number, 5)}')
Enter a number to compare: 20
The maximum number is 5
The maximum number is 20
Our code now works successfully. The int() converts the string input to an integer to compare the two other integers.
Summary
Congratulations on making it to the end of this tutorial. To summarize, we raise the TypeError: ‘>’ not supported between instance of ‘str’ and ‘int’ when trying to use the greater than comparison operator between a string and an integer. This TypeError generalizes all comparison operators, not just the > operator.
To solve this error, convert any string values to integers using the int() function before comparing them with integers.
To learn more about Python, specific to data science and machine learning, go to the online courses page for Python.
Have fun and happy researching!
Introduction
Problem: How to fix – TypeError: '<' not supported between instances of 'str' and 'int'
in Python?
Example:
num = input(«Enter a number: «) print(‘The minimum number is: ‘, min(1, 2, 3)) print(«The minimum number: «, min(5, num, 25)) |
Output:
Enter a number: 20
The minimum number is: 1
Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 3, in
print(“The minimum number: “, min(5, num, 25))
TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’
Explanation:
- In the above example, you can see that when three
integers
were passed to themin
function, then the program gave us the output by fetching the minimum number, i.e.,1
. - But, when we passed a
string
value to themin
function along with two otherintegers
, then it resulted in aType Error: '<' not supported between instances of 'str' and 'int'
.
Hence the TypeError
occurred when we compared two variables whose datatypes are completely different (a string and integer in this case.)
Before proceeding further, let us have a quick look at some of the key concepts that will help you to identify and avoid TypeErrors
in the future.
💡 Python TypeError
TypeError
is one of the most common standard Python exceptions that occur in Python. Python throws aTypeError
when an operation is carried out on an incorrect/unsupported object type.- For example, using the < (less than) operator on an integer and a string value will throw a TypeError.
- This is because integers and strings are two different types of data types and cannot be compared with the help of operators used for comparisons such as <, >, >=, <=, ===, !==.
📖 Read more here: What is TypeError in Python?
📍 The following example will be used to demonstrate the solutions to our mission- critical question:- How to fix TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’?
Example
The following table lists the tenure and the corresponding Fixed Deposit rates of a certain bank.
Tenure | FD Interest Rates |
6 months to 364 days | 5.25% |
18 months 1 day to 1 year 364 days | 6.00% |
1 year 1 day to 18 months | 5.75% |
2 years to 2 years 364 days | 6.00% |
3 years to 4 years 364 days | 5.65% |
5 years to 10 years | 5.50% |
In the following code, when the user selects a certain tenure the corresponding FD rates shall be displayed. Also, if tenure is greater than 1 year 1 day to 18 months, then customer is a “Prime Customer” else “Normal Customer”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
print(«»« Tenure FD 1. 6 months to 364 days 5.25% 2. 18 months 1 day to 1 year 364 days 6.00% 3. 1 year 1 day to 18 months 5.75% 4. 2 years to 2 years 364 days 6.00% 5. 3 years to 4 years 364 days 5.65% 6. 5 years to 10 years 5.50% ««») option = input(«Select the Tenure (1 — 6): «) if option < 4: print(«Normal Customer») if option == 1: print(«Rate = «, 5.25) if option == 2: print(«Rate = «, 6.00) if option == 3: print(«Rate = «, 5.75) else: print(«Prime Customer») if option == 4: print(«Rate = «, 6.00) if option == 5: print(«Rate = «, 5.65) if option == 6: print(«Rate = «, 5.50) |
Output:
The above error occurred because if option < 4
is an unsupported operation. Let’s solve this issue using the following methods.
📌 Method 1: Using int()
Instead of accepting the user input as a string, you can ensure that the user input is an integer with the help of int()
method.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
print(«»» 1. 6 months to 364 days 2. 18 months 1 day to 1 year 364 days 3. 1 year 1 day to 18 months 4. 2 years to 2 years 364 days 5. 3 years to 4 years 364 days 6. 5 years to 10 years ««») option = int(input(«Select the Tenure (1 — 6): «)) if option < 4: print(«Normal Customer») if option == 1: print(«Rate = 5.25%») if option == 2: print(«Rate = 6.00%») if option == 3: print(«Rate = 5.75%») else: print(«Prime Customer») if option == 4: print(«Rate = 6.00%») if option == 5: print(«Rate = 5.65%») if option == 6: print(«Rate = 5.50%») |
Output:
Explanation: int(value)
function converts the user-input to an integer value. Thus now you can compare two values of the same data type using the <
operator.
📌 Method 2: Using a Custom Function
Instead of manually typecasting the string value to an integer you can also define a function to convert it to a string.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
def convert(x, cast): x = cast(x) return x print(«»» 1. 6 months to 364 days 2. 18 months 1 day to 1 year 364 days 3. 1 year 1 day to 18 months 4. 2 years to 2 years 364 days 5. 3 years to 4 years 364 days 6. 5 years to 10 years ««») def fd(option): if int(option) < 4: print(«Normal Customer») if option == 1: print(«Rate = 5.25%») if option == 2: print(«Rate = 6.00%») if option == 3: print(«Rate = 5.75%») else: print(«Prime Customer») if option == 4: print(«Rate = 6.00%») if option == 5: print(«Rate = 5.65%») if option == 6: print(«Rate = 5.50%») choice = input(«Select the Tenure (1 — 6): «) x = convert(choice, int) fd(x) |
Output:
1. 6 months to 364 days
2. 18 months 1 day to 1 year 364 days
3. 1 year 1 day to 18 months
4. 2 years to 2 years 364 days
5. 3 years to 4 years 364 days
6. 5 years to 10 years
Select the Tenure (1 – 6): 5
Prime Customer
Rate = 5.65%
🐰 Bonus Read: Python Typecasting
Type Casting is the process of converting a literal of one type to another type. Typecasting is also known as explicit type conversion. Python inbuilt functions like int()
, float()
and str()
are used for typecasting.
For example:
int()
function can accept afloat
orstring
literal as an input and return a value ofint
type.
li = [’50’, ‘50.25’, 100] my_int = int(li[0]) # typecasting str to int my_float = float(li[1]) # typecasting str to float my_str = str(li[2]) # typecasting float to str print(«»«Original Typecasted {0} {1} {2} {3} {4} {5} ««».format(type(li[0]), type(my_int), type(li[1]), type(my_float), type(li[2]), type(my_str))) |
Output:
Conclusion
Hence, in this article, you learned what is Type Error: '<' not supported between instances of 'str' and 'int'
and the possible causes and solutions of the error.
In general, if you are getting a TypeError
in your code, take a moment to verify that the data you are operating on is actually of the type you would expect it to be.
You can rectify this error by manually converting the datatype so that the comparison is performed between values of the same datatypes.
Recommended Tutorials:
- [Solved] TypeError: Can only Concatenate str (not “int”) to str
- [Solved] TypeError: not all arguments converted during string formatting
- [Solved] TypeError: Can’t Multiply Sequence by non-int of Type ‘float’ In Python?
Please subscribe and stay tuned for more tutorials. Happy learning! 📚
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.
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:
- TypeError: ‘module’ object is not callable in python
- TypeError: ‘nonetype’ object is not callable
- TypeError: ‘NoneType’ object is not iterable in Python
- TypeError: ‘set’ object is not subscriptable in Python
- TypeError: ‘str’ object does not support item assignment
- TypeError: ‘<‘ not supported between instances of ‘NoneType’ and ‘int’
Hi, my name’s Nathaniel Kirk. I’m interested in learning and sharing knowledge about programming languages. My strengths are C, C++, Python, HTML, CSS, Javascript, and Reactjs. If you have difficulty with them, don’t worry. I’m here to support you.
Name of the university: PTIT
Major: IT
Programming Languages: C, C++, Python, HTML, CSS, Javascript, Reactjs
You can only compare items using mathematical operators if they have the same numerical data type. If you try to compare a string and an integer, you’ll encounter an error that says “not supported between instances of ‘str’ and ‘int’”.
In this guide, we discuss what this error means and why it is raised. We walk through an example scenario where this error is present so we can talk about how to fix it.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
typeerror: ‘>’ not supported between instances of ‘str’ and ‘int’
Strings and integers cannot be compared using comparison operators. This is because strings and integers are different data types.
Python is a statically typed programming language. You have to manually change the type of a data if you need to compare it with a value of another type.
For instance, suppose you want to convert a string to an integer. You have to manually convert the string to an integer before the comparison will work.
The “typeerror: ‘>’ not supported between instances of ‘str’ and ‘int’” error occurs when you try to perform a “greater than” comparison on a string and an integer.
This error can happen with any comparison operation, such as a less than (<), less than or equal to (<=), or greater than or equal to (>=).
An Example Scenario
We build a program that calculates the letter grade a student has earned in a test.
To start, ask a user to insert a numerical grade which we will later convert to a letter grade using an input() statement:
numerical_grade = input("What grade did the student earn? ")
Then, use an “if” statement to calculate the student’s numerical grade:
if numerical_grade > 80: letter = "A" elif numerical_grade > 70: letter = "B" elif numerical_grade > 60: letter = "C" elif numerical_grade > 50: letter = "D" else: letter = "F" print(letter)
This code compares numerical_grade to a series of values. First, our code checks if numerical_grade is greater than 80. If it is, the value of “letter” becomes “A”. Otherwise, our code checks the next “elif” statement.
If the “if” and “elif” statements all evaluate to False, our code sets the value of “letter” to “F”.
At the end of our program, we print the letter grade a student has earned to the console.
Run our code and see what happens:
What grade did the student earn? 64 Traceback (most recent call last): File "main.py", line 3, in <module> if numerical_grade > 80: TypeError: '>' not supported between instances of 'str' and 'int'
Our code does not run successfully. Our code asks us to insert a student grade. When our code goes to make its first comparison, an error is returned.
The Solution
The input()
method returns a string. This means our code tries to compare a string (the value in “numerical_grade”) to an integer.
We solve this problem by converting “numerical_grade” to an integer before we perform any comparisons in our code:
numerical_grade = int(input("What grade did the student earn? "))
The int() method converts the value the user inserts into our program to an integer.
Try to run our code again:
What grade did the student earn? 64 C
Our code works successfully. This is because we now compare two integer values instead of an integer and a string.
Conclusion
The “typeerror: ‘>’ not supported between instances of ‘str’ and ‘int’” error is raised when you try to compare a string to an integer.
To solve this error, convert any string values to integers before you attempt to compare them to an integer. Now you’re ready to solve this common Python error in your code like a professional software developer.