简体   繁体   中英

TypeError: '<' not supported between instances of 'list' and 'int

Im not able to solve these isssues: File "c:\Data\test_while.py", line 7, in if x < 0 or x > 5: TypeError: '<' not supported between instances of 'list' and 'int'

x = []

while True:
    try:
        x.append(int(input("Please enter a number 1 - 5: ")))
        if x < 0 or x > 5:
                ValueError
                print ("Wrong numbers...")
                continue
        if x == 0:
            break
        print (x)
    except ValueError:
        print ("Oops!  Only numbers. Try again...")

print(x[:-1])

You're putting the input in the list immediately and then trying to compare the entire list to the integers. Since you want to keep this data in the list and also want to break/continue from the middle of the loop, the best way to deal with this would be:

x.append(int(input("Please enter a number 1 - 5: ")))
    if x[-1] < 0 or x[-1] > 5:
        # etc.
    if x[-1] == 0:
        break

This way you access your most recent input but keep the input in your list.

You probably don't want to add the number to the list when it is outside your bounds. Only append it when it passes checks.

Also, in this bit of code there probably isn't a need to use exceptions, but if you feel the need or curious, you can do so as I have below. I don't know why you have ValueError in your bounds check because it doesn't raise that way.

x = []

while True:
    try:
        cur = int(input("Please enter a number 1 - 5: "))
        if cur < 0 or cur > 5:
            raise ValueError("Wrong numbers ...")
        if cur == 0:
            break
        x.append(cur)
        print(cur)
    except ValueError as e:
        if "invalid literal" in str(e):
            print("Oops!  Only numbers. Try again...")
        elif "Wrong numbers" in str(e):
            print(e)
        else:
            raise

print(x)

It would be nice if the type check for integer conversion would raise a TypeError instead of ValueError when invalid literal happens, but I'm sure there is some good reason that isn't the case.

You are appending the input directly into the list and that is why you can't compare it. Slicing the list with x[-1] will give you the number that was entered last into the list which you can then compare to 0 and 5.

x = []

while True:
    try:
        x.append(int(input("Please enter a number 1 - 5: ")))
        if x[-1] < 0 or [-1] > 5:
                ValueError
                print ("Wrong numbers...")
                continue
        if x == 0:
            break
        print (x)
    except ValueError:
        print ("Oops!  Only numbers. Try again...")

print(x[:-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM