'或'在elif中忽略else语句并关闭循环

时间:2016-08-09 16:58:38

标签: python loops if-statement

对以下两个脚本之间的行为差​​异感到非常困惑

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'

如果您运行这两个脚本

,结果如下
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$

正如您所看到的,test.py按预期工作,但test2.py立即退出而不是执行else语句。非常困惑,两个脚本之间的唯一区别是elif语句中的“或'exit'”。

1 个答案:

答案 0 :(得分:1)

你应该改变:

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

为:

exit

否则True评估为Type TEventRecord = record Length : dword; Reserved : dword; RecordNumber : dword; end; TEventLog = array of TEventRecord ; Var Buffer : TEventLog; begin Setlength (Buffer, $FFF0); // ReadEventLog(@buffer[0],...) end. ,就像任何(非空)字符串一样。