【问题标题】: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如何从用户那里获取输入,将它们放入列表中,然后从中随机选择一个,而无需多次询问
【发布时间】:2021-07-13 14:28:20
【问题描述】:

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

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

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

我该如何解决这个问题?

【问题讨论】:

  • fav_hobbies = hobbies.split(" ") 将根据您提供的分隔符将一个字符串拆分为多个字符串(在这种情况下," ",即空格。您可以将其替换为逗号或多个字符) .

标签: python random


【解决方案1】:

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

假设您接受空格分隔的输入,您可以这样做:

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(',')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    相关资源
    最近更新 更多