0

I'm very new to coding, so I apologize if the answer is very simple, but I'm currently trying to code a magic 8 ball game. I want the computer to give a random string from a list I made, to the user when they give an input. Here's the code I made so far:

import random
print("Welcome to the Magic 8 Ball Game!")

#Create phrases the maigc 8 ball will say to the user
phrases = ["Ask again", "Reply hazy, try again.", "I do see that in your near future...", "My sources say no", "Very possible", "Yes. Very soon."]
#Ask the user to ask a question to start the game
answer = input("The game has started. Ask a question.\n")
#Make a loop


for i in answer:

     print(random.choice(phrases))

When I run the code, instead of giving a single string to the user, it'll randomly give out multiple strings. I think I might not be using the for loop correctly...

2 Answers 2

2

It should be an infinite loop which breaks by a certain condition for example when a user types none or something:

import random
print("Welcome to the Magic 8 Ball Game!")

#Create phrases the maigc 8 ball will say to the user
phrases = ["Ask again", "Reply hazy, try again.", "I do see that in your near future...", "My sources say no", "Very possible", "Yes. Very soon."]
#Ask the user to ask a question to start the game
answer = input("The game has started. Ask a question.\n")
#Make a loop


while True:
    print(random.choice(phrases))
    answer = input("Ask a question.\n")
    if answer == 'None':
        break
Sign up to request clarification or add additional context in comments.

Comments

0

It is for a beginner a surprise but also for an advanced programmer sometimes a hard to find bug in for item in some_variable if the variable is for some reason a string. In such case the for loop iterates over the single characters of the string as items.

The loop in the question will be run as many times as many characters were in the user input. This explains what you have experienced.

Other issues with your code are avoided if you use the in the other answer proposed code replacing if answer == 'None': with if not answer:.

Happy coding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.