[VISIBLE ONLY LOCALLY] Optionally view what the website will look like at another time (in PDT):
Credit: Chris Piech, with modifications by Lisa Yan
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:
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? yes Ask a yes or no question:
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 8ball.py (if you are on Mac)
py 8ball.py (if you are on PC).
def main(): while True: input("Ask a yes or no question: ") # remember, this is a comment # BEGIN YOUR CODE # END YOUR CODE
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 runningsum.py or
py runningsum.py again.
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 (
elif) to print out the selected answer.
To generate a random integer, you can do the following:
num = random.randint(min, max)
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
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
statement = input("Type in something: ") if statement == "": print("nothing entered") else: print(statement)