Magic 8-ball: file handling instructions
Having really long lists in Python is not very efficient. Not only that, it makes it more difficult
to debug. A much better way to handle the list of responses would be to use a text file.
Task 1
Create a text file containing all the 20 possible responses (each on a new line) and save this
as ‘responses.txt’.
responses.txt
It is certain
It is decidedly so
Without a doubt
Yes definitely
You may rely on it
…
Task 2
Copy the following code (making sure that you read the comments in red explaining what the
code is doing).
import random
import time
# Open the 8-ball responses text file
f = open(‘responses.txt’,=‘r’)
# Read the whole file and store each line in a list
responses = f.readlines()
# Ask the user to input a Yes/No style question
question = input(“Please ask me a Yes/No question”)
# Pause for 2 seconds to make it look like the computer is thinking
time.sleep(2)
# Print a response at random from the list
print(random.choice(responses))
Year 8, Unit 5, Lesson 6, Worksheet 2
© Pearson Education Ltd, 2019. Copying permitted for purchasing institution only. This material is not copyright free.