简体   繁体   English

为什么我的if else语句被忽略

[英]Why is my if else statement being ignored

So I'm writing a code that searches a dictionary for a user inputed key. 因此,我正在编写一个在字典中搜索用户输入键的代码。 To do so, I have the user type in their desired key, have the definition to that key be appended to a list, and then printing the list. 为此,我让用户键入所需的键,将该键的定义附加到列表中,然后打印该列表。

For some odd reason my if serachT in dictionary line gets ignored. 由于某种奇怪的原因,我的if serachT in dictionary行中的if serachT in dictionary被忽略了。 The program will jump to the else, completely skips the if. 程序将跳转到else,完全跳过if。 I have removed the else to verify that the if does work. 我已经删除了else,以验证if是否起作用。 Any ideas on why adding else ignores the 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()

You should be populating your dictionary first, then start looking things up. 您应该先填充字典,然后再开始查找。 Fortunately, this is trivial in your case: 幸运的是,在您的情况下,这是微不足道的:

def create_dictionary():
    with open("textToEnglish2014.csv", newline="") as fo:  # note the newline parameter!
        reader = csv.reader(fo)
        return dict(reader)

(Note that now your function name makes sense, unlike before) (请注意,与以前不同,现在您的函数名称很有意义)

Now you can do lookups easily: 现在,您可以轻松进行查找:

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM