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

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

下面是我的代码。我是编码新手,所以我需要你的帮助。 我不知道为什么会出现此错误,因为当我尝试 type() 时,它显示的是 class int.

我的代码

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

但我在 maxmin

上收到此错误

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

python 中的输入始终被视为字符串,因此需要进行转换。第 3 行将为您做到这一点。另外,您知道 python 可以处理任何大小的数字吗?你可以大干一场!

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

试试这个,

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

你的版本可能更短,

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