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?
CodePudding user response:
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")
CodePudding user response:
Replace if toss != acceptables:
by if toss not in acceptables: