0

I am trying to make a prompt in Python 2.7. I have an infinite loop that will get the user's input using str(raw_input('$> ')). Then, it checks a bunch of 'if' and 'elif' statements (each one is a particular command) to see what to do with the entered command. I have also disabled KeyboardInterrupt through a 'try... except' statement, and added an 'exit' command. Here is where the problem lies. The 'exit' command runs well, printing 'Bye' and then quitting. However, so does every other unknown command.

I have tried using the built-in quit() and exit() functions and sys.exit(), but none of them fix the problem. I have also encased my 'if' statements in a while loop that checks if it is not the 'exit' command, and then used the else statement to quit. However, it just prints Command "exit" not found.

My question is a) why Python will execute that code for any statements after it, and b) what to do to fix this, if possible.

My theory for a) is that because Python is interpreted line by line, it reads that line and for whatever reason, executes it. However, if the command matches, it stops looking at the 'if' statement and executes the code for the entered command.

Here is a simplified version of my code, and thank you in advance.

from sys import exit as die

while True:
    msg = str(raw_input('$> '))
    if msg == 'test':
        print '123'
    elif msg == 'quit' or 'exit':
        print 'Bye'
        die()   
    elif msg == 'test2':
        print '456'
    else:
        print 'Command "%s" not found' % (msg)

If I run the 'test2' command, or an unkown command 'foo', the program will print 'Bye' and exit.

Noah
  • 95
  • 1
  • 14
  • 2
    Can you provide [MCVE](https://stackoverflow.com/help/mcve)? – rutsky Mar 08 '15 at 00:27
  • @rutsky Updated post. Is that good, or do you need anything else? – Noah Mar 08 '15 at 00:36
  • 4
    That update included the necessary detail. `if a == b or c` does not do what you are expecting it to do. Please see the [linked question](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) for details. – poke Mar 08 '15 at 00:38

1 Answers1

1
msg == 'quit' or 'exit'

means

(msg == 'quit') or 'exit'