简体   繁体   中英

How to print a random string from a list, when given an input? (Python)

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...

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM