首页 > 解决方案 > 如何从用户那里获取输入,将它们放入列表中,然后从中随机选择一个,而无需多次询问

问题描述

这是我学习编程的第四天,所以我对它很陌生。我试图在一个问题中获取用户的信息(爱好)并将它们保存到一个列表中,然后将他们选择的爱好之一回馈给用户。这就是我想出的

import random

fav_hobbies = []
hobbies = input("what are your favourite hobbies?(cooking, writing,ect) ").lower()
fav_hobbies.append(hobbies)

situation = input("so are you bored now?(answer with yes or no): ").lower()
if situation == "yes":
     print("you should try " + random.choice(fav_hobbies))

elif boredom_situation == "no":
     print("awesome! have a nice day!")

问题是,它不是在用户选择的单词中选择一个单词,而是打印他们所说的所有内容。

我该如何解决?

标签: pythonrandom

解决方案


您只是接受来自用户的字符串并将其按原样存储而无需拆分。

假设您接受空格分隔的输入,您可以在以下位置执行此操作:

fav_hobbies = list(input("what are your favourite hobbies?(cooking, writing,ect) ").lower().split())
import random

fav_hobbies = list(input("what are your favourite hobbies?(cooking, writing,ect) ").lower().split())

situation = input("so are you bored now?(answer with yes or no): ").lower()
if situation == "yes":
     print("you should try " + random.choice(fav_hobbies))

elif boredom_situation == "no":
     print("awesome! have a nice day!")

如果您使用其他分隔符,,则可以将其添加到split(',')


推荐阅读