[英]How to get input from user, put them into a list and then choose a random one from them without having to ask multiple times
It's my 4th day learning programming so I'm very new to it.这是我学习编程的第 4 天,所以我对它很陌生。 and I'm trying to get the user's info(hobbies) in one question and save them into a list then give back the user one of the hobbies they chose.
并且我试图在一个问题中获取用户的信息(爱好)并将它们保存到列表中,然后将他们选择的一种爱好还给用户。 this what I've came up with
这是我想出的
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!")
The problem is that instead of choosing a word among the words that user has chosen it just prints all of the things they said.问题在于,它不是在用户选择的单词中选择一个单词,而是打印他们所说的所有内容。
How do I fix this?我该如何解决?
You are just accepting a string from the User and storing it as it is without splitting.您只是接受来自用户的字符串并按原样存储它而不拆分。
Assuming that you are accepting a space separated input , You can do this in:假设您接受空格分隔的 input ,您可以在以下位置执行此操作:
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!")
If you use some other separator like ,
you can just add it to split(',')
如果您使用其他一些分隔符,例如
,
可以将其添加到split(',')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.