2013-09-21 28 views
0

在Michael Dawson的書「絕對初學者的Python」一書中,我學到了很多東西,並且正在嘗試使用舊的Magic 8-Ball作爲練習來製作一個新程序作爲我的靈感。以下是我到目前爲止的代碼。字典和elif

它工作到一個點...隨機生成的數字生成,但elif似乎並沒有工作。我知道有更好的方法和更簡單的方法,但我這樣做是爲了加強我對字典的理解。

我已經把幾個打印語句,看看我是否得到一個數字選擇和else語句是如果一切都不好。由於代碼現在我得到的是打印的數字和其他產生「不計算。退出工作正常。我也已經證實字典罰款使用已註釋的打印」球「聲明。

所以我的問題是爲什麼ELIF語句,似乎不是過程中產生的隨機數。誰曾答案有衷心的感謝和讚賞。

# Import the modules 
import sys 
import random 

# define magic 8-ball dictionary 
ball = {"1" : "It is certain.", 
     "2" : "Outlook is good.", 
     "3" : "You may rely on it.", 
     "4" : "Ask again later.", 
     "5" : "Concentrate and ask again.", 
     "6" : "Reply is hazy, try again later.", 
     "7" : "My reply is no.", 
     "8" : "My sources say no"} 
# for items in ball.items(): 
#    print(items) 

ans = True 

while ans: 
    question = input("Ask the Magic 8 Ball a question: (press enter to quit) ") 

    answer = random.randint(1,8) 
    print(answer) 

    if question == "": 
     sys.exit() 

    elif answer in ball: 
     response = ball[answer] 
     print(answer, response) 
    else: 
     print("\nSorry", answer, "does not compute.\n")  

回答

1

您正在用字母查找字典,而鍵是字典中的字符串。所以,你必須將數字轉換爲字符串str

變化

answer = random.randint(1,8) 

answer = str(random.randint(1,8)) 
+0

就是這樣。非常感謝。我現在知道我錯了什麼地方:混合str和int。 –

+0

@EricBaltrush歡迎:)請考慮upvoting和接受這個答案如果有幫助http://meta.stackexchange.com/a/5235 – thefourtheye

+0

在幾個很好的答案中,你的第一個,正是我所需要的。儘管從所有這些貢獻中我都很欣賞所有的答案。 Python是一個偉大的社區。 –

1

字符串"1"不是int 1。所以answer其實不是ball。 嘗試將其轉換爲answer = str(random.randint(1,8))

+0

我得到它,感謝您的評論。解決了我的問題。 –

3

random.randint()返回一個整數。你的字典的鍵都是字符串。因此,當你做answer in ball,它將總是False,因爲"1" != 1

你能做什麼或者是做使所有的按鍵整數(去掉引號),或使answer的字符串:

answer = str(random.randint(1,8)) 

請注意,您不應該在這裏使用elif。如果你的輸入是什麼都不是,你的ifelif將是真的,大多數時候你不想要這個。取而代之的是,改變你的elif/else只是一個if/else

if question == "": 
    sys.exit() 

if answer in ball: 
    response = ball[answer] 
    print(answer, response) 
else: 
    print("\nSorry", answer, "does not compute.\n")  

的最後一件事。 answer將始終在ball中,因爲您動態創建了字典。在這裏,您可以使用dict.get()。例如:

if not question: # You can do this instead 
    sys.exit() 

print(ball.get(answer)) 
+0

非常感謝。基於評論已經嘗試和成功使用第一個字符串,然後改變字典爲數字,它的工作很好,現在我完全理解我的錯誤和修復。謝謝大家! –

+0

@EricBaltrush你非常歡迎!不要忘記[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)! – TerryA