chilledheat chilledheat - 1 year ago 72
Python Question

Using a dictionary as an answer key for user input

This is meant to only break out of the loop when the user enters a file extension that is in the 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":
elif fileExt != ext_dict:
print('Please enter a correct file extension (.pdf, .txt, etc..) type "help" for a list of extensions')
print("\"%s\" has been selected" % fileExt)

Still relatively new to python, any pointers in the right direction would be great

Answer Source

First, your help_dict is not a dict, it's a set.

Second: you're comparing a string with a set - which of course won't never ever compare equal. Testing if a set contains an element is done with the in operator: if something in myset: - and for non-appartenance you simply use not in. IOW, you want:

elif fileExt not in ext_dict:
   # XXXX
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download