[英]Why is my if else statement being ignored
因此,我正在编写一个在字典中搜索用户输入键的代码。 为此,我让用户键入所需的键,将该键的定义附加到列表中,然后打印该列表。
由于某种奇怪的原因,我的if serachT in dictionary
行中的if serachT in dictionary
被忽略了。 程序将跳转到else,完全跳过if。 我已经删除了else,以验证if是否起作用。 关于为什么添加else的任何想法都会忽略if?
import csv
def createDictionary():
dictionary = {}
found = []
searchT = input("What are you seraching for ")
fo = open("textToEnglish2014.csv","r")
reader = csv.reader(fo)
for row in reader:
dictionary[row[0]] = row[1]
if searchT in dictionary:
found.append(dictionary[row[0]])
print(found)
elif searchT not in dictionary:
i = 0
#print("NF")
#exit()
print(found)
return found
createDictionary()
您应该先填充字典,然后再开始查找。 幸运的是,在您的情况下,这是微不足道的:
def create_dictionary():
with open("textToEnglish2014.csv", newline="") as fo: # note the newline parameter!
reader = csv.reader(fo)
return dict(reader)
(请注意,与以前不同,现在您的函数名称很有意义)
现在,您可以轻松进行查找:
>>> dictionary = create_dictionary()
>>> searchT = input("What are you searching for? ")
What are you searching for? hello
>>> dictionary.get(searchT) # returns None if searchT is not in dictionary
goodbye
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.