Prologue:
Welcome back! Today we’re building a Magic 8-Ball. You ask it a yes-or-no question, and it gives you a random answer like “Definitely!” or “No way.”
Along the way, you’ll learn about lists, one of the most useful tools in Python.
Let’s begin!
Chapter 1: The inner magic!
Open IDLE, click File > New File, and save it as magic_8_ball.py. Then type this in:
import random
answers = ["Yes!", "No way.", "Maybe...", "Ask again later.", "Definitely!", "I wouldn't count on it."]
print("Welcome to the Magic 8-Ball!")
while True:
question = input("Ask a yes-or-no question (or type quit): ")
if question == "quit":
print("Goodbye!")
break
print(random.choice(answers))
Press F5 and start asking! Here’s an example:
Welcome to the Magic 8-Ball!
Ask a yes-or-no question (or type quit): Will I pass my math test?
No way.
Ask a yes-or-no question (or type quit): Will it rain tomorrow?
Definitely!
Ask a yes-or-no question (or type quit): quit
Goodbye!
Don’t worry, the 8-Ball is just picking randomly. It doesn’t actually know about your math test!
Chapter 2: Understanding the magic!
1. Lists
A list stores a bunch of values in one variable. You make one with square brackets [ ] and put commas between the items. Our answers list holds 6 answers. Scratch has lists too: they’re under “Variables” with the “Make a List” button.
2. random.choice()
random.choice(answers) grabs one random item from the list. Every time you ask a question, you get a different answer.
3. == vs =
This one trips up a lot of beginners:
=stores a value:question = input(...)==checks if two things are equal:if question == "quit":
4. break
while True: repeats forever, just like the forever block. So how do we stop it? break jumps out of the loop right away. When you type quit, the program says goodbye and breaks out.
Chapter 3: Future Steps
Nice job! You now know how to use lists, one of the tools real programmers use every single day. In Part 8, we’re going to get visual and draw pictures with code using Python’s turtle.
CHALLENGE
Add at least 3 of your own answers to the
answerslist. Try something funny, like “Ask your mom.”
If you get stuck or have any questions, feel free to contact me! And leave a comment with the funniest answer you added!
