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
广告