繁体   English   中英

给定输入时,如何从列表中打印随机字符串? (Python)

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

我对编码很陌生,所以如果答案很简单,我很抱歉,但我目前正在尝试编写一个魔术 8 球游戏。 我希望计算机在用户提供输入时从我制作的列表中提供一个随机字符串给用户。 这是我到目前为止所做的代码:

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

当我运行代码时,它不会给用户一个字符串,而是随机给出多个字符串。 我想我可能没有正确使用 for 循环......

它应该是一个无限循环,它会在某个条件下中断,例如当用户键入 none 或某些内容时:

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

对于初学者来说是一个惊喜,但对于高级程序员来说,如果变量由于某种原因是字符串,有时很难for item in some_variable错误。 在这种情况下,for 循环将字符串的单个字符作为项进行迭代。

问题中的循环将运行与用户输入中的字符数一样多的次数。 这解释了你所经历的。

如果您在其他答案中使用建议的代码替换if answer == 'None':if not answer: ,则可以避免代码的其他问题。

快乐编码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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