Python Program for a Magic 8 Ball
Beginner · Games and random numbers
A Magic 8 Ball is a toy that gives a random answer to a yes or no question, such as "It is certain" or "Ask again later". This program keeps the answers in a list and picks one at random for each question.
Program
Question: Will I pass my exam? Magic 8 Ball says: Without a doubt. Question: Will it rain tomorrow? Magic 8 Ball says: Without a doubt. Question: Should I learn Python? Magic 8 Ball says: Without a doubt.
How it works
- The possible answers are stored in a list: some say yes, some say no and some are vague.
random.choice(answers)picks one at random for each question, so the answers change on every run.- The question itself does not affect the answer, which is how the real toy works too.
- The
questionslist stands in for questions the user would type, as shown in theinput()comment.
Other ways to write it
Asking until the user types quit
Is Python fun? -> Maybe. Will I win the match? -> Definitely! Goodbye!
The loop stops at "quit", so the last question is never asked. In the interactive version a while True loop keeps asking until the user types quit, and break ends it.
Some answers more likely than others
Answer 1: Yes Answer 2: No Answer 3: Ask again later Answer 4: Ask again later Answer 5: Ask again later
random.choices() with weights makes some answers come up more often, here "Yes" about half the time. It returns a list, so [0] takes the single answer out of it.
Try it yourself
Add three answers of your own, and print "That is not a question!" when a question does not end with "?".
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises