使用字典作为用户输入的答案键

时间:2016-11-17 15:57:01

标签: python dictionary

这意味着当用户输入字典中的文件扩展名时,只会突破循环:

def ext_input():
    ext_dict = {'doc', 'docx', 'pdf', 'rtf', 'txt', 'wps', 'csv'}
    while True:
        print('Enter the file extension (.pdf, .txt, etc..) type "help" for a list of extensions')
        fileExt = input()
        if fileExt == "help":
            print(ext_dict)
            return
        elif fileExt != ext_dict:
            print('Please enter a correct file extension (.pdf, .txt, etc..) type "help" for a list of extensions')
        else:
            print("\"%s\" has been selected" % fileExt)
            break

对于python来说还是比较新的,任何指向正确方向的指针都会很棒

2 个答案:

答案 0 :(得分:1)

首先,您的help_dict不是dict,而是set

第二:你将一个字符串与一个集合进行比较 - 当然赢得了永远不会比较平等。测试集合是否包含元素是使用in运算符完成的:if something in myset: - 对于非appartenance,您只需使用not in。我想,你想:

elif fileExt not in ext_dict:
   # XXXX

答案 1 :(得分:0)

您的ext_dict应该是一个列表而不是字典(它不是,请参阅Bruno的答案),它允许修改此代码:

def ext_input():
    ext_dict = ['doc', 'docx', 'pdf', 'rtf', 'txt', 'wps', 'csv']
    while True:
        print('Enter the file extension (.pdf, .txt, etc..) type "help" for a list of extensions')
        fileExt = input()
        if fileExt == "help":
            print(ext_dict)
            return
        elif fileExt not in ext_dict:
            print('Please enter a correct file extension (.pdf, .txt, etc..) type "help" for a list of extensions')
        else:
            print("\"%s\" has been selected" % fileExt)
            break