'Question about try and except using lists

So I had made this program thing in which it asks you to enter a random number, The number can only be from the list; [1, 2, 3, 4, 5, 6, 10] and nothing else.

I want to make if so if it is not from the list acceptables = [1, 2, 3, 4, 5, 6, 10] it will print "Illegal Number" and exit() program. But I cannot do it .

Here is what I tried:

invalids = ['7', '8', '9', '11']
acceptables = [1, 2, 3, 4, 5, 6, 10]
try :
    toss = int(input("Toss a number from 1 to 6 (10 included): "))
except ValueError:
    print("Invalid")

if toss != acceptables:
    print("Illegal Numbers!")
    time.sleep(2)
    exit()

But it doesn't seem to work, Can anyone help?



Solution 1:[1]

This is because if the except block is executed, the toss variable has no value. Best choice would be to include the later code into the try block:

invalids = ['7', '8', '9', '11']
acceptables = [1, 2, 3, 4, 5, 6, 10]
try :
    toss = int(input("Toss a number from 1 to 6 (10 included): "))
    if toss not in acceptables:
        print("Illegal Numbers!")
        time.sleep(2)
        exit()
except ValueError:
    print("Invalid")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anshumaan Mishra