Magic 8 Ball Program In Python

In this tutorial, we will be writing a Magic 8 Ball program in Python. We will be asking the user to think of the question they wanna ask the Magic 8 Ball and then we will randomly choose an answer from a pre-defined list of answers.

Python Magic 8 Ball

import random

def magic8ball():
    response = input("(Press 'any key' for answer and 'quit' to exit)\nWhat is your question?\n")
    Eightball_answers = [
        "It is certain",
        "Outlook good",
        "You may rely on it",
        "Ask again later",
        "Concentrate and ask again",
        "Reply hazy, try again",
        "My reply is no",
        "My sources say no"
        ]
    
    if response == "quit":
        print("Have A Good Day!")
    else:
        print(random.choice(Eightball_answers), "\n")
        magic8ball()

magic8ball()

We start by importing a module whose functions we will be using in the program. So we use import random. Random module is used to find a random answer from the list of answers.

We define a function called magic8ball(). This is our function which will generate and answer and display it to the user. Inside this function we start by Asking the user to think of a question to which he or she wants answered. They then press ‘any key’ to get the answer or ‘quit’ to exit the program. This input is read using input() and stored in the variable response . We are using \n to print the sentence on a new line.

We have also created a list of answers stored in Eightball_answers. They include “It is certain”, “Outlook good”, “You may rely on it”, “Ask again later”, “Concentrate and ask again”, “Reply hazy, try again”, “My reply is no”, “My sources say no”.
NOTE: You can add or remove these answers.

Next we use an if…else statement to check if the input was ‘quit’ or not. If it was quit then we display an exiting message and exit the program. If the user pressed any other key then we choose a random answer from our list of answers and display it. We use random.choice(Eightball_answers) for this. The answer is chosen from the list randomly and printed using print().

After printing the answer we make a recursive call to magic8ball() so that we can offer the user a chance to ask another question or quit.

Output

Press 'Enter' for answer and 'q' to exit)
What is your question?
t                               #any key pressed
Ask again later

(Press 'Enter' for answer and 'q' to exit)
What is your question?
h                               #any key pressed
My sources say no

(Press 'Enter' for answer and 'q' to exit)
What is your question?
quit
Have A Good Day

So here it is, a simple magic 8 ball program in python.

Also read,

Leave a Reply

Your email address will not be published. Required fields are marked *