打印Python列表

zxlwwiss  于 2023-01-04  发布在  Python
关注(0)|答案(2)|浏览(135)
drinks = ['cola', 'water', 'beer', 'wine']

drinks = raw_input ("What did you drink? " + print drinks)

所以,基本上我想让程序向用户显示问题,然后打印出可能的答案。用户应该将其中一个输入回程序中。我尝试了上面的代码,但它不起作用。在raw_input之前打印drinks有点没有意义。我想你也可以这样做:

drinks = ['cola', 'water', 'beer', 'wine']

drinks1 = raw_input("Hai, wanna have a look at the most popular drinks here?")
if drinks1 == "yes":
print drinks

drinks2 = raw_input("So, what did you drink?")

......但是,在Python中,有没有用户可以选择的更简单的任务列表呢?
提前感谢您的回答。

bmp9r5qi

bmp9r5qi1#

一个非常简单的解决方案是

drinks = ['cola', 'water', 'beer', 'wine']

drink = raw_input ("What did you drink? %s" % ', '.join(drinks))

if drink in drinks:
    print('you chose ' + drink)
else:
    print('invalid choice')

使用join从列表中生成一个字符串。

hlswsv35

hlswsv352#

你可以使用striplower函数来编写一个泛型程序,其他的看起来都没问题。

drinks = ['cola', 'water', 'beer', 'wine']

user_input = raw_input("Hai, wanna have a look at the most popular drinks here?")

if user_input.strip().lower() == "yes":
   print drinks

drinks2 = raw_input("So, what did you drink?")

相关问题