2014-12-05 15 views
0

在這個程序中,我正在製作一本字典。我做了詞典,當我打字時,它說詞典不存在於詞典中,爲什麼?

當我運行這個程序,並在程序中要求我search meaning菜單1,但是當我鍵入單詞404(這是在字典中),它說:Word donot exist in dictionary。這個問題從哪裏來?

print("This is a dictioinary") 
print("\t\t\tWelcome to Geek Translator Game") 
dictionary={"404":"Message not found","googler":"person who seaches on google"} 
choose=None 
while(choose!=0): 
    choose=input('''0.Exit 
1.search meaning 
2.Add Word 
3.Replace meaning''') 

if choose is 0: 
    print("bye") 
if choose is 1: 
    word=input("Enter the word\n") 
    if word in dictionary: 
     meaning=dictionary[word] 
     print(meaning) 
    else: 
     print("Word donot exist in dictionary") 
if choose is 2: 
    word=input("Enter the word\n") 
    if word in dictionary: 
     print("Word already exists in dictionary") 
     print("Try replacing meaning by going in option 3") 
    else: 
     defination=input("Enter the defination") 
     dictionary[word]=defination 
if choose is 3: 
    word=input("Enter the term\n") 
    if word in dictinary: 
     meaning=input("Enter the meaning\n") 
     dictionary[word]=meaning 
    else: 
     print("This term donot exist in dictionary") 
+1

'input'在Python 2.x的是真的'的eval(的raw_input(...))',所以'word'是多少' 404'(其中*不是字典中的*)而不是字符串''404'(是)。 **使用'raw_input'。** – jonrsharpe 2014-12-05 10:51:58

+0

另外,您應該使用'=='而不是'is'(您正在測試的是平等,而不是身份)。 – 2014-12-05 10:53:00

回答

3

input()解釋用戶輸入作爲Python表達式。如果輸入404,則Python將該解釋爲整數。但是,您的字典中包含字符串

您必須輸入"404"加上引號才能使其正常工作。你更好選擇是使用raw_input()代替,以獲得原始輸入用戶鍵入沒有它不必被格式化爲一個Python表達式:

word = raw_input("Enter the word\n") 

做這個無處不在,你使用input()現在。對於你的用戶菜單輸入,你應該使用int(raw_input("""menu text"""))而不是input()。您可能對Asking the user for input until they give a valid response感興趣,以瞭解有關如何向用戶提供特定輸入的更多信息。

接下來,您正在使用is來測試用戶選擇。這個工作根本就是巧合,因爲Python已經實現了小整數,你確實得到了相同的0對象一遍又一遍,is測試工作。對於幾乎所有比較要使用==代替但是:

if choose == 0: 
    # ... 
elif choose == 1: 
    # etc. 
+0

謝謝, 你清除我的5-6概念在你的1解決方案 你是一個天才 – 2014-12-05 11:07:45