Reputation: 1839
def find_acronym():
# if search term in database returns acronym and expansion
for abbr, text in acronyms.items():
if abbr == search_analyte.get():
expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
elif str(search_analyte.get()) in text:
expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
# if search term not in database , returns message DOES NOT WORK PROPERLY!
if search_analyte.get() not in text or abbr != search_analyte.get():
expansion.insert(0.0,'"{0}"{1} \n {2}\n'.format(search_analyte.get(),' is not in the database.','Add,if appropriate'))
I use this function to search through a dictionary of acronyms and their associated expanded meaning in the format { ACRONYM: text details, ACRONYM2: its test,...}
The algorithm 'works in the sense that it retrieves the acronym and text for any search item, but it also always returns the text message from the last if condition meant to discover whether the item is in the database or not. I clearly am illogical or I don't understand how loops work in Python.
Upvotes: 1
Views: 150
Reputation: 24812
if I understand what you want to achieve, here is a way to do it:
def find_acronym():
found=False
# if search term in database returns acronym and expansion
for abbr, text in acronyms.items():
if abbr == search_analyte.get():
found=True
expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
elif str(search_analyte.get()) in text:
found=True
expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
# if search term not in database , returns message DOES NOT WORK PROPERLY!
if not found:
expansion.insert(0.0,'"{0}"{1} \n {2}\n'.format(search_analyte.get(),' is not in the database.','Add,if appropriate'))
Upvotes: 1
Reputation: 13244
The way you have it now, the last test is running after the FOR loop has completed, so you can't compare against abbr
and text
usefully any more.
You want something like:
def find_acronym():
found = False
# if search term in database returns acronym and expansion
for abbr, text in acronyms.items():
if abbr == search_analyte.get():
expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
found = True
elif str(search_analyte.get()) in text:
expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
found = True
# if search term not in database
if not found:
expansion.insert(0.0,'"{0}"{1} \n {2}\n'.format(search_analyte.get(),' is not in the database.','Add,if appropriate'))
Upvotes: 1