Python魔法8球程式



魔法8球是一款玩具,可以對各種問題給出通常是“是”或“否”的答案,因此非常適合做決定或消磨時間。在這裡,讓我們討論一下如何開發一個模擬魔法8球工作的基本Python程式。

這將包括教學習者如何處理使用者輸入、程式生成響應的能力,以及為了改程序序的使用而採用純粹的基本決策。

什麼是魔法8球程式?

魔法8球程式是一個應用程式,允許使用者輸入問題並進入預先確定的可能的答案列表,程式隨後選擇一個隨機的答案並將其呈現給使用者。該程式還包含用於以非對抗性方式回答敏感問題的邏輯。這使得程式更加完善,使其適合市場上的任何使用者,而不會直接冒犯任何一方。

構建魔法8球程式的步驟

1. 設定你的環境

Python已安裝在你的系統上。使用任何文字編輯器或IDE,如PyCharm、Visual Studio Code或Python IDLE來編寫和執行你的程式碼。

2. 匯入所需的模組

random模組對於這個程式很重要,因為它允許我們從我們的答案列表中隨機選擇一個答案。

匯入random模組

import random

3. 定義函式

建立一個名為**magic_8_ball()**的函式,其中將包含程式的核心邏輯。

4. 建立一個答案列表

responses列表包含魔法8球可以提供的許多型別的答案。

CODE:  responses = [
   "Yes, definitely.",
   "As I see it, yes.",
   "Reply hazy, try again.",
   "Cannot predict now.",
   "Do not count on it.",
   "My sources say no.",
   "Outlook not so good.",
   "Very doubtful."
]

5. 程式結構

程式的結構是不斷提示使用者輸入問題。在每個問題之後,它從列表中提供一個隨機答案,並詢問使用者是否要繼續。

if __name__ == "__main__":
   while True:
      magic_8_ball()
      play_again = input("Do you want to ask another question? (yes/no): ").strip().lower()
      if play_again != 'yes':
         print("Goodbye!")
         break

魔法8球程式的實現

import random
def magic_8_ball():
   responses = [
      "It is certain.",
      "It is decidedly so.",
      "Without a doubt.",
      "Yes, definitely.",
      "You may rely on it.",
      "As I see it, yes.",
      "Most likely.",
      "Outlook good.",
      "Yes.",
      "Signs point to yes.",
      "Reply hazy, try again.",
      "Ask again later.",
      "Better not tell you now.",
      "Cannot predict now.",
      "Concentrate and ask again.",
      "Don't count on it.",
      "My reply is no.",
      "My sources say no.",
      "Outlook not so good.",
      "Very doubtful."
   ]

   neutral_responses = [
      "The future is uncertain.",
      "Only time will tell.",
      "That's a mystery even to me!",
      "Some things are best left unknown.",
      "Focus on the present!"
   ]

   sensitive_keywords = ["destroy", "end", "die", "death", "apocalypse", "war", "kill"]

   question = input("Ask the Magic 8 Ball a question: ").lower()

   # Check for sensitive keywords
   if any(word in question for word in sensitive_keywords):
      answer = random.choice(neutral_responses)
   else:
      answer = random.choice(responses)

   print("Shaking the Magic 8 Ball...")
   print("The Magic 8 Ball says: " + answer)

if __name__ == "__main__":
   while True:
      magic_8_ball()
      play_again = input("Do you want to ask another question? (yes/no): ").strip().lower()
      if play_again != 'yes':
         print("Goodbye!")
         break

輸出

Magic 8 Ball
python_projects_from_basic_to_advanced.htm
廣告