Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a more compact if statement in Python

I have been working on a calculator in Python. There is nothing wrong with the calculator, but I would like to make part of the code in it more optimized/shortened.

Here is the code that I want optimized/shortened:

   #In this code i check to see if they have entered a valid option in my calculator
   option = int(input("Option: "))
   if option != 0:
      if option != 1:
         if option != 2:
             if option != 3:
                if option != 4:
                   print("Please enter a valid choice")
                   #As you can see it needs to check 5 numbers

if you can figure out a way to shorten the code above it would be MUCH appreciated!

like image 251
Jonty Morris Avatar asked Dec 05 '25 13:12

Jonty Morris


1 Answers

If you have all your options in a list this would be the quickest and easiest way.

if option not in [1,2,3,4]:
   print("Not a valid choice")
like image 189
Henrik Andersson Avatar answered Dec 10 '25 16:12

Henrik Andersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!