Let’s build The Magic 8-Ball!
A Magic 8-Ball is a fun toy where you ask it a “yes or no” question, shake it, and it gives you a random answer about the future. We can build our own digital version using the if, elif, and else statements you just learned.
To make the answer a surprise every time, we will learn one new trick: the random tool!
The Magic 8-Ball Code
Here is the complete code for your game. You can type this into Python and run it!
Python
import random
print("🔮 Welcome to the Python Magic 8-Ball! 🔮")
# 1. Ask the player for their question
user_question = input("Ask a 'Yes' or 'No' question: ")
# 2. Pick a random number between 1 and 5
magic_number = random.randint(1, 5)
print("Shaking the Magic 8-Ball...")
# 3. Use conditions to match the number to a secret answer!
if magic_number == 1:
print("Answer: Yes, definitely! 🌟")
elif magic_number == 2:
print("Answer: My sources say no. 🌧️")
elif magic_number == 3:
print("Answer: Ask again later. The magic is sleepy. 💤")
elif magic_number == 4:
print("Answer: Without a doubt! ✨")
else:
# If the number is 5, it goes to the else block
print("Answer: Very doubtful... 🐢")
How It Works (The Magic Secrets)
Here is exactly what the code is doing behind the scenes:
import random: This tells Python to go to its toolbox and bring out the “random” tool. This tool lets Python pick numbers unpredictably, just like rolling dice!input(...): This puts a message on the screen and waits for you to type your question and press Enter. It makes your program interactive.random.randint(1, 5): This is the core magic! It tells Python to pick a random whole integer (a number with no decimals) between1and5. It saves that secret number inside themagic_numbervariable.ifandelif: Now, Python acts like a referee. It checks the secret number. If Python rolled a1, it prints the first answer. If it rolled a2, it skips the first one and prints the second answer.else: If Python checked all theelifblocks and none of them matched, it falls into theelsebucket. In our game, if the number is5, it skips1through4and prints the final “Very doubtful” answer.