The idea behind an 8-Ball is you ask the eight ball a yes or no question, and it tells you the answer. Except that the answer it chooses is randomly selected from a set of prefabricated responses.

A real life 8-Ball

Write a program that continuously prompts the user for a yes or no question, and then randomly selects from 5 predetermined answers:

  • Without a doubt.
  • Yes.
  • Ask again later.
  • No.
  • Karel thinks so.

Here is an example run of the program.

Ask a yes or no question: Will Ghana win the world cup?
only Karel knows

Ask a yes or no question: Is Karel married?
good question!

Ask a yes or no question: Is my real name Nick
Without a doubt

Ask a yes or no question: 8-Ball, are you using random numbers?

Ask a yes or no question: 

Infinite Loop

We've implemented part of this program for you---specifically, the infinite loop part which continuously asks for user input). We've left you the job of getting the program to answer with the 5 canned answers above.

Take a look at what we've implemented below. If you run this code as-is, what does this program do? Try it out in PyCharm by running the file! Remember that you can run your program in Pycharm's Terminal by typing python3 (if you are on Mac) or py (if you are on PC).

def main():
    while True:
        input("Ask a yes or no question: ")

        # remember, this is a comment

        # END YOUR CODE

Quitting an infinite loop

This program runs forever! To exit a program that runs forever, hit Ctrl-C on your keyboard while in the Terminal. You should then be able to run your program via the python3 or py again.

Choices and random numbers

One way to choose randomly between 5 answers is to associate each answer with a number and make use of Python's ability to randomly pick numbers. Then, depending on which number is picked, you can use conditional statements (if, else, elif) to print out the selected answer.

To generate a random integer, you can do the following:

num = random.randint(min, max)

min and max are the minimum and maximum integers, respectively that the variable num can take on. For example:

num = random.randint(10, 20)

will store a random number between 10 and 20, inclusive, in the variable num.

Bonus: Extension

Your current program runs forever. How would you change the while loop conditional (currently True) to exit when the user types nothing (just presses Enter)?

Hint: Here's a program that outputs "nothing entered" when the user types in nothing (just presses Enter). Otherwise the program prints the user input. How can you use a similar idea and apply it to the while loop?

statement = input("Type in something: ")
if statement == "":
    print("nothing entered")