Arsh Gupta
Arsh Gupta

Reputation: 15

TypeError: '>' not supported between instances of 'int' and 'str' in my code where the values are already integers

Below is my code. I am new to coding, so I need your help. I don't know why I am getting this error, because when i tried for the type() of all it is showing class int.

My code

n = int(input("Enter the length of list:"))
lst = input("Enter the numbers with a space:")
numbers = lst.split()
if len(numbers) == n:
    maxn = -2147483647
    minn = 2147483647
    for number in numbers:
        y = int(number)
        if y > maxn:
            maxn = number
        if y < minn:
            minn = number
    print(maxn, minn)
else:
    print("Numbers greater or less than length")

But I am getting this error on max and min

Traceback (most recent call last): File "test.py", line 9, in if y > maxn: TypeError: '>' not supported between instances of 'int' and 'str'

Upvotes: 1

Views: 128

Answers (2)

Prathamesh
Prathamesh

Reputation: 1057

Try this,

n = int(input("Enter the length of list:"))
lst = input("Enter the numbers with a space:")
numbers = lst.split()
y=0
if len(numbers) == n:
    maxn = -2147483647
    minn = 2147483647
    for number in numbers:
        y = int(number)
        if y > maxn:
            maxn = int(number)#changed here
        if y < minn:
            minn = int(number)#changed here
    print(maxn, minn)
else:
    print("Numbers greater or less than length")

a shorter version of your could be,

n = int(input("Enter the length of list:"))
lst = input("Enter the numbers with a space:")
numbers = lst.split()
numbers = [ int(x) for x in numbers ]
print(max(numbers),min(numbers))

Upvotes: 0

JimmyCarlos
JimmyCarlos

Reputation: 1952

Inputs in python are always treated as strings, so need to be converted. Line 3 will do that for you. Also, did you know python can handle any size of number? You can go big!

n = int(input("Enter the length of list:"))
lst = input("Enter the numbers with a space:")
numbers = lst.split()
if len(numbers) == n:
    maxn = -2147483647
    minn = 2147483647
    for number in numbers:
        y = int(number)
        if y > maxn:
            maxn = y
        if y < minn:
            minn = y
    print(maxn, minn)
else:
    print("Numbers greater or less than length")

Upvotes: 1

Related Questions