MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
从之前的课程中,我了解到我需要格式化字典中的数据,以便它可以在代码中使用。但我处于非常初级的水平,格式化数据后我陷入困境。
def format_data(choice):
"""Format ingredients into printable format: water, milk, coffee, cost"""
water = MENU[user_choice]['ingredients']["water"]
milk = MENU[user_choice]['ingredients']["milk"]
coffee = MENU[user_choice]['ingredients']["coffee"]
cost = MENU[user_choice]['ingredients']["cost"]
user_choice = input("What would you like? (espresso/latte/cappuccino").lower()
in
运算符检查该饮料是否在
MENU
字典中
在MENU
字典中,则使用饮料选择作为
MENU
的键来查找配方(成分和数量)
他们的饮料(例如。
MENU[choice]['ingredients']
)
resources
字典中的相同成分中减去该数量
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 3000,
"milk": 2000,
"coffee": 1000,
}
# go into a 'forever' loop and prompt the user for their drink choice
while True:
choice = input("choice: ")
# if input line has a 'q' in it then quit (break out of loop)
if 'q' in choice:
print("all done")
break
# if input line is not a known drink then prompt to try again
if choice not in MENU:
print("don't have that on the menu try again")
continue
# if we get here we know its a known drink so get the recipe
# for the chosen drink and assign it to the the recipe dictionary
recipe = MENU[choice]['ingredients']
# now go through the recipe for the chosen drink and
# for each ingredient subtract the quantity of that
# ingredient used from the resources dictionary
for ingredient, quantity in recipe.items():
resources[ingredient] -= quantity
# report the drink was made
print ("made you a", choice)
# report the remaining resources after the drink was made
print ("remaining resources are:")
for ingredient, quantity in resources.items():
print(f"{ingredient:6} {quantity:6}")