1

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?

2
  • 2
    != should be not in as you want to test if the value is in your list not that the value is your list Commented Feb 5, 2022 at 13:45
  • I would recommend having another input() call at the end instead of sleeping for 2s. Commented Feb 5, 2022 at 13:49

2 Answers 2

2

Replace if toss != acceptables: by if toss not in acceptables:

Sign up to request clarification or add additional context in comments.

2 Comments

That doesn't seem to be the sole issue. The variable toss is undefined if except block is executed. Hence there's an error
This is not the main problem here, of course if the wrong value is entered it won't be defined. The problem is that the if statement is wrong.
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") 

2 Comments

Although not critical in this scenario: everything aside from the toss assignment should be in the try-else-block.
Its not usually a good idea to have too big a scope for try/except - makes handling complicated when your code isnt sure what blew up. Keep except only around the int conversion. However, you did catch a logic flaw in their handling when toss fails. The else clause in try/except/else could be used.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.