簡體   English   中英

為什么我的if else語句被忽略

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM