Python程序决策控制问题

Rob*_*ypt -1 python if-statement

我正在尝试创建一个代码库,我可以在其中存储随着时间的推移找到的代码片段并检索它们.到目前为止,这是我的代码.

# Python Code Library User Interface

import sys

class CodeLib:
    codes = []
    option = ['help (-h)', 'list (-l)', 'import (-i)', 'quit (-q)']

#What does the user want to do?
    print "Welcome to the Code Library"
    print "What would you like to do? \n %s" % option
    choice = raw_input()
    print choice
    if choice == 'quit' or '-q':
        sys.exit()
    length = len(choice)
# Getting name of file to import if user chooses import before
# viewing the code list
    if choice[0] == 'i':
        _file_ = choice[6:length]
    elif choice[:2] == '-i':
        _file_ = choice[2:length]
# imports file if user chose import before viewing code list
    if choice[0:5] == 'import' or choice [0:2] == '-i':
        import _file_
# If user chose option other than import at beginning
# then perform option chosen then give ability to do something else
    while choice != 'quit' or '-q':
# provides basic help menu
        if choice == 'help' or '-h':
            print
            print '''(list or -l) brings up a list of code snippet names
(import or -i)/file_name brings up the code snippet you chose \n'''
# provides list of code files
        elif choice == 'list' or '-l':
            print codes
            print option[2], "file name"
            _file2_ = raw_input()
            import _file2_
# imports code file
        else:
            _file2_ = raw_input()
            import _file2_
# Next user option                  
        print "What would you like to do?"
        choice = raw_input
Run Code Online (Sandbox Code Playgroud)

现在我知道到目前为止这是非常不完整的.但我遇到的问题是无论我作为选择进入什么.程序执行第一个if语句,退出程序.我已经注释掉了第一个if语句并再次尝试.但无论我输入什么作为选择.它在while循环中执行第一个if语句,而我只是陷入循环中.所以我不确定有什么问题,但有人可以帮助我吗?

Bar*_*zKP 7

"或'-q'"部分检查字符串'-q'是否为false,对于任何非空字符串都是如此.将此行更改为:

if choice == 'quit' or choice == '-q':
Run Code Online (Sandbox Code Playgroud)

  • OP也应该检查argparse模块这样的东西,它消除了很多针,如果 - 然后http://docs.python.org/2/library/argparse.html#module-argparse (3认同)