我怎样才能从字典中找到输入的值

我正在为一个学校项目编写这段代码,它是这样的:


valid_entries = ['y', 'n', 'hatchback', 'estate', 'saloon']

model_options = {

    'Hatchback' : 535000,

    'Saloon' : 495000,

    'Estate' : 625000

}

total_price = 0


model_chosen = input("Which car model do you want to buy?\n> ")

while model_chosen not in valid_entries:

    print("Invalid Input\nTry again")

    model_chosen = input("Which car model do you want to buy?\n> ")

有没有办法可以访问这些值并将其与输入进行比较并将其添加到分数中?


小怪兽爱吃肉
浏览 138回答 2
2回答

ITMISS

您可以使用以下语法访问该值:dict[key]。例如,在您的代码中,models_options[Estate] 的值为 625000。您实际上并不需要列表 valid_entries。您可以尝试以下代码:valid_entries = ['y', 'n', 'hatchback', 'estate', 'saloon']model_options = {    'Hatchback' : 535000,    'Saloon' : 495000,    'Estate' : 625000}total_price = 0model_chosen = input("Which car model do you want to buy?\n> ")while model_chosen not in model_options:    print("Invalid Input\nTry again")    model_chosen = input("Which car model do you want to buy?\n> ")total_price+=model_options[model_chosen]print(total_price)

慕桂英546537

值为 model_options[model_chosen],你到底想做什么?你能做到吗:total += model_options[model_chosen]。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python