在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")
就是這樣。非常感謝。我現在知道我錯了什麼地方:混合str和int。 –
@EricBaltrush歡迎:)請考慮upvoting和接受這個答案如果有幫助http://meta.stackexchange.com/a/5235 – thefourtheye
在幾個很好的答案中,你的第一個,正是我所需要的。儘管從所有這些貢獻中我都很欣賞所有的答案。 Python是一個偉大的社區。 –