0% found this document useful (0 votes)
7 views1 page

Y8 5 L6 WS2 Final

The document provides instructions for creating a Magic 8-ball program in Python that utilizes a text file for responses. It outlines two tasks: creating a 'responses.txt' file with 20 possible answers and implementing a code snippet to read from this file and provide a random response to a Yes/No question. The code includes comments explaining each step of the process.

Uploaded by

sircarlinmolapo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Y8 5 L6 WS2 Final

The document provides instructions for creating a Magic 8-ball program in Python that utilizes a text file for responses. It outlines two tasks: creating a 'responses.txt' file with 20 possible answers and implementing a code snippet to read from this file and provide a random response to a Yes/No question. The code includes comments explaining each step of the process.

Uploaded by

sircarlinmolapo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

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.

You might also like