【问题标题】:Taking user input as string and printing a variable Python [duplicate]将用户输入作为字符串并打印变量 Python [重复]
【发布时间】:2022-07-05 09:08:55
【问题描述】:

我试图获取用户输入,然后将该输入转换为变量以打印出一个列表。

food_list = ["Rice", "l2", "l3"]
Rice = []
l2 = []
l3 = []
answer = input("What item would you like to see from the list")
if answer in food_list:
      print("answer")

我希望输出是打印 Rice 列表,而不仅仅是像以前那样的字符串“Rice”。输入会将其作为字符串,但我想将输入转换为列表变量。

【问题讨论】:

  • 你的预期输出是什么?
  • 发布的代码缺少第 1 行中“Rice”一词后的右引号,因此报告错误。一旦修复,如果响应为 Rice,则编写的代码将始终返回 Rice。否则,它什么也不返回。程序的期望功能是什么?

标签: python variables user-input


【解决方案1】:

你可以用字典来做到这一点:

~/tests/py $ cat rice.py
food_list ={"Rice":"Rice is nice" }

print("What item would you like to see from the list")
answer = input(": ")
if answer in food_list.keys():
      print(food_list[answer])
~/tests/py $ python rice.py
What item would you like to see from the list
: Rice
Rice is nice

【讨论】:

    【解决方案2】:

    Python 的 in 关键字功能强大,但它只检查列表成员身份。

    你想要这样的东西:

    food_list = ["Rice", "Cookies"]
    answer = input("What item would you like to see from the list")
    
    # if the food is not in the list, then we can exit early
    if answer not in food_list:
      print("Food not found in the list")
    
    # we know it's in the list, now you just filter it.
    for food in food_list:
      if food == answer:
        print(food)
    

    编码愉快!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多