0

Really confused by the difference in behavior between the two following scripts

test.py

while True:
    print 'Enter commands, blah blah'
    input = raw_input(">> ") #get keyboard input
    if (input == 'string'):
        print '\n' #whatever task
    elif (input == 'quit'):
        exit()  #exits the application
    else:
        print 'Invalid'

test2.py

while True:
    print 'Enter commands, blah blah'
    input = raw_input(">> ") #get keyboard input
    if (input == 'string'):
        print '\n' #whatever task
    elif (input == 'quit' or 'exit'):
        exit()  #exits the application
    else:
        print 'Invalid'

Here's the result if you run both of these scripts

bred@loaf:~/py$ python test.py
Enter commands, blah blah
>> a
Invalid
Enter commands, blah blah
>> quit
bred@loaf:~/py$ python test2.py
Enter commands, blah blah
>> a
bred@loaf:~/py$

As you can see, test.py works as expected, but test2.py exits immediately rather than performing the else statement. Very confused, the only difference between the two scripts is the "or 'exit'" in the elif statement.

T. Zack Crawford
  • 7,646
  • 3
  • 11
  • 18
  • `'exit'` is always true. Try it: `if 'exit': print 'hello'`; you'll see that it prints `hello` 100% of the time. – Charles Duffy Aug 09 '16 at 17:00
  • 1
    http://stackoverflow.com/questions/20002503/why-does-a-b-or-c-or-d-always-evaluate-to-true is perhaps an even better duplicate. – Charles Duffy Aug 09 '16 at 17:02

1 Answers1

1

You should change:

    elif (input == 'quit' or 'exit'):

to:

    elif (input == 'quit' or input == 'exit'):
    #                     ---^---

otherwise exit evaluate as True like any (non-empty) string.

Graham
  • 7,431
  • 18
  • 59
  • 84
Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31