台北來的土包子
 
Python  Dict 運用 -Magic 8 Ball 神奇8號球

Python Dict 運用 -Magic 8 Ball 神奇8號球

神奇 8 號球是一個用來玩占卜的玩具,如果遇到一個難以選擇的問題時,手邊有這顆球,就可以試著向它尋求解答。
8號球中藏著20種答案,其中 10 個是肯定的答案,5 個是否定,另外5個是模稜兩可或是再問一次,詳細的說明請參考維基百科

# Magic Ball
#https://www.george.tw/2020/05/01/python-dict-magic-8-ball/
import random

# https://zh.wikipedia.org/wiki/神奇八號球
magicMap={
      1:'It is certain (這是必然)',
      2:'It is decidedly so  (肯定是的)',
      3:'Without a doubt  (不用懷疑)',
      4:'Yes, definitely  (毫無疑問)',
      5:'You may rely on it  (你能依靠它)',
      6:'As I see it, yes  (如我所見,是的)',
      7:'Most likely  (很有可能)',
      8:'Outlook good  (外表很好)',
      9:'Yes  (是的)',
      10:'Signs point to yes  (種種跡象指出「是的」)',
      11:'Reply hazy try again  (回覆攏統,再試試)',
      12:'Ask again later  (待會再問)',
      13:'Better not tell you now  (最好現在不告訴你)',
      14:'Cannot predict now  (現在無法預測)',
      15:'Concentrate and ask again  (專心再問一遍)',
      16:'Don\'t count on it  (想的美)',
      17:'My reply is no  (我的回覆是「不」)',
      18:'My sources say no  (我的來源說「不」)',
      19:'Outlook not so good  (外表不太好)',
      20:'Very doubtful  (很可疑)'
}

while True:
   question=input("Enter your question:")
   magicNum = random.randint(1,20)
   print("Your question  =>" + question)
   print("My answer =>" + magicMap[magicNum])
   if (magicNum > 16 or magicNum < 11):
         break
      

一開始先引入 random 的函式庫
這 20 個答案是不變的,所以直接使用『字典』(dict) 的特性 { key : value},等會產生 1-20 的亂數後,可以找到對應的答案 。
由於 11 -15 的答案不是確定的,若亂數介於此範圍,則讓使用者再問一次。因此利用了 while 迴圈,加上 if 的判斷,來達到此目的。

程式原始碼: GitHub

發表迴響