python - Why is my if else statement being ignored -
so i'm writing code searches dictionary user inputed key. so, have user type in desired key, have definition key appended list, , printing list.
for odd reason if seracht in dictionary
line gets ignored. program jump else, skips if. have removed else verify if work. ideas on why adding else ignores if?
import csv def createdictionary(): dictionary = {} found = [] searcht = input("what seraching ") fo = open("texttoenglish2014.csv","r") reader = csv.reader(fo) row in reader: dictionary[row[0]] = row[1] if searcht in dictionary: found.append(dictionary[row[0]]) print(found) elif searcht not in dictionary: = 0 #print("nf") #exit() print(found) return found createdictionary()
you should populating dictionary first, start looking things up. fortunately, trivial in case:
def create_dictionary(): open("texttoenglish2014.csv", newline="") fo: # note newline parameter! reader = csv.reader(fo) return dict(reader)
(note function name makes sense, unlike before)
now can lookups easily:
>>> dictionary = create_dictionary() >>> searcht = input("what searching for? ") searching for? hello >>> dictionary.get(searcht) # returns none if searcht not in dictionary goodbye
Comments
Post a Comment