-2

I am very new to programming and am working on catching invalid user inputs for a little pet project I am building to help me learn python.

I realized once I was done with this program a user could mess up the execution of the code by entering an invalid input durning the begging stages of the program so I attempted catching this and ending the program with the following code. It triggers every-time —even with a valid entry— and I believe it's because at least one of the or statements will always be true. Is this correct?

#Sub Code:Invalid Choice Handler
if user_choice != "1" or user_choice != "2" or user_choice != "3":
    sys.exit("You typed an invalid choice, you loose.")

I 'fixed' the problem with the below code but it feels backwards to me. Is the below an acceptable way to catch invalid inputs or is there a better way I am ignorant to?

#Sub Code:Invalid Choice Handler
if user_choice == "1" or user_choice == "2" or user_choice == "3":
    pass
else:
    sys.exit("You typed an invalid choice, you loose.")

I am asking to learn so thank you very much for any help!

Nymexx
  • 1
  • 1

1 Answers1

0

You could do this, allows to add or delete valid choices easily

valid_choices = [1,2,3]
if user_choice not in valid_choices:
    sys.exit("You typed an invalid choice, you loose.")
Prithvi Raj
  • 1,611
  • 1
  • 14
  • 33