1

So I was making my own terminal with a list of commands and a series of if-statements to check them. If the command does not exist, it returns an error. If the input is contained in the list of commands, regardless of which command, it will execute only the first if-statement. E.g. I enter 3 and it will still return '1 or 2'. This has to do with the 'or' statement, but I'm not sure why. If I use if-statements with only one variable the code runs fine, but I'd like to check for multiple commands:

  1. For efficiency
  2. So multiple spellings of a command can be excepted. e.g. '1' and 'one'.

I know this is caused by the or function, but I can't see why. Anyone have any ideas?

Below is an example code, simplified, but produces the same results as my actual script:

commands = ['1', '2', '3', '4']
if command in commands:
    if command == '1' or '2':
        print('1 or 2')
    elif command == '3' or '4':
        print('3 or 4')
    else:
        print('UNDEFINED COMMAND')
else:
    print("INVALID COMMAND")```
God-status
  • 141
  • 2
  • 14
  • 1
    Yeah, use `command in ['1', '2']`, or `command == '1' or command == '2'` – gribvirus74 Mar 05 '21 at 21:47
  • 3
    Just so you get the terminology correct, `or` is not a statement, it is an operator. Your if expression is interpreted as `(command == '1') or '2'`. The way the `or` operator works is, if the left side is true, it is returned. Otherwise, the right side is returned. So, if command was '1', it would return True. If command was anything other than '1', it would return '2'. – Tim Roberts Mar 05 '21 at 21:53
  • 1
    This is a good first question -- it includes code, some effort to understand what's going on, and a well-made [mre]. Kudos! Some useful links to help you find your feet here: [tour], [what's on-topic](/help/on-topic), [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953). Welcome to SO! – Pranav Hosangadi Mar 05 '21 at 22:00

0 Answers0