In: Computer Science
Write a program that simulates a Magic 8 Ball, which is a fortune-telling toy that displays a random response to a yes or no question. In the student sample programs for this book, you will find a text file named 8_ball_responses.txt. The file contains 12 responses, such as “I don’t think so”, “Yes, of course!”, “I’m not sure”, and so forth. The program should read the responses from the file into a list. It should prompt the user to ask a question, then display one of the responses, randomly selected from the list. The program should repeat until the user is ready to quit.
use the template below:
def ___ function:
# open a file
#__ _ _ _ _
#close file
___( )
Contents of 8_ball_responses.txt:
Yes, of course!
Without a doubt, yes.
You can count on it.
For sure!
Ask me later.
Iím not sure.
I canít tell you right now.
Iíll tell you after my nap.
No way!
I donít think so.
Without a doubt, no.
The answer is clearly NO.
Here is the python code with comments:
# import the random module so that we can use the choice function
import random
# The function to get the list of responses from the file
def function():
stream = open('8_ball_responses.txt', 'rt')
# we delimit the responses with \n
listofresponses = stream.read().split('\n')
# now close the stream
stream.close()
return listofresponses
listofresponses = function()
# You can uncomment the below 2 lines to see the list of responses
# for i in listofresponses:
# print(i)
while True:
print('Ask a the magic ball a question (press -1 to exit) :')
# convert the input to a string
userinput = str(input())
# if the input is -1 then break
if(userinput == '-1'):
break
# use random.choice to randomly pick a list element
print('The magic ball says: ' + random.choice(listofresponses))
Here is code image to understand the indentation:
Here is the output: