【问题标题】:how to display a list that has numbers when the number is inputted输入数字时如何显示包含数字的列表
【发布时间】:2021-10-07 01:04:17
【问题描述】:
options = ["1. Hyundai", "2. Benz", "3. BMW", "4. Honda", "5. Toyota", "6. GMC", "7. Cadillac", "0.Exit"]

for i in options:
    print(i)
answer = int(input("choose a number from the list above "))
for index in range(len(options)):
    if answer == options[0]:
        print(f"{options} is a nice car")


if  answer == 0:
    print("Goodbye")

我想知道在他们输入他们喜欢的汽车号码后如何获得输出“(他们的选择)是一辆好车”。

【问题讨论】:

  • int 1 不是字符串 "1. Hyundai"。考虑使用dict?而且每一行都有更多的错误......
  • 使用options[0] Wher Well工作时有超过10个选项。您应该使用更通用的设计。比如只使用输入值作为列表的索引。
  • 如果用户输入0,您将打印Exit is a nice car

标签: python python-3.x python-2.7


【解决方案1】:
options = ["1. Hyundai", "2. Benz", "3. BMW", "4. Honda", "5. Toyota", "6. GMC", "7. Cadillac", "0.Exit"]

for i in options:
    print(i)
answer = int(input("choose a number from the list above "))
if  answer == 0:
    print("Goodbye")
else:
    print(f"{options[answer-1]} is a nice car")

【讨论】:

    【解决方案2】:

    我们必须打印“他们的车”,所以我们不需要 answer==options[index],如果答案是 1,我们只需要打印 options[0],如果答案是 2,则打印 options[1],options [2] 如果答案是 3,以此类推,那么您编辑的代码将是:

    options = ["1. Hyundai", "2. Benz", "3. BMW", "4. Honda", "5. Toyota", 
    "6. GMC", "7. Cadillac", "0.Exit"]
    
    for i in options:
        print(i)
    answer = int(input("choose a number from the list above "))
    if answer in range(1,8):
        print(f"{options[answer-1]} is a nice car")
    
    
    elif  answer == 0:
        print("Goodbye")
    else:
        print("wrong option chosen")
    

    检查缩进错误,因为我在写答案时自己编辑了它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2014-10-16
      • 1970-01-01
      • 2020-07-05
      相关资源
      最近更新 更多