Search code examples
pythonpython-3.xtypestraceback

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'


Solution

  • 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))