0

I want to be able to do something like this, where inputs of 1, "D" or "dog" will all call do_something(), whereas any other input will call do_something_else().

command = input("Type a command")
if command == (1 or "D" or "dog"):
   do_something()
else:
    do_something_else()

Currently, this does not work, because Python is evaluating the truthiness of (1 or "D" or "dog"), which is always True, of course. Then, since command is also a true string, do_something will always be called.

I know how to do this one way: if command == 1 or command = "D" or command = "dog". This works fine; however, it involves a lot of repetition, and I'm sure there must be some way to shorten that.

I suppose I could also make a list of valid commands, valid_commands = [1,"D","dog"] and check if command in valid_commands, but that seems like a workaround, rather than the ideal approach.

Somatic
  • 193
  • 7

1 Answers1

1

You should use in operator:

command = input("Type a command")
if command in ["1","D","dog"]:
   do_something()
else:
   do_something_else() 
Ali Nikneshan
  • 3,500
  • 27
  • 39