遇到Python字典操作的问题



我这里有一些代码,当我对每个成分使用单独的if语句时可以工作,但是当使用for循环编辑字典中的值时失败。我似乎无法弄清楚为什么我的报告屏幕在输入饮料订单后没有改变,或者在输入多个饮料订单后检查资源时似乎会变负)。这是一台虚拟咖啡机。有问题的代码位于for循环的末尾和check resources函数中。我试着调试没有成功。下面是代码:

MENU = {
"espresso": {
"ingredients": {
"water": 50,
"milk": 0,
"coffee": 18,
},
"cost": 1.50,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.50,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.00,
}
}
resources = {
"water": 100,
"milk": 0,
"coffee": 18,
}

water = resources["water"]
milk = resources["milk"]
coffee = resources["coffee"]
money_profit = 0

# TODO 1. Create a report of how much water, milk, coffee, and money you have used
def report(water_ingredient, milk_ingredient, coffee_ingredient, money_in_box):
print("The coffee machine has:")
print(f"Water: {water_ingredient}ml")
print(f"Milk: {milk_ingredient}ml")
print(f"Coffee: {coffee_ingredient}g")
print(f"Money: ${format(money_in_box, '.2f')}")

# TODO 2. Check if resources are available for coffee order
def check_resources(ingredients):
for item in ingredients:
if resources[item] < ingredients[item]:
print(f"Sorry, not enough {item}!")
return False
return True

def money(user_choice):
global money_profit
print(f"The cost of {user_choice} is ${format(MENU[user_choice]['cost'], '.2f')}.n Please insert coins: ")
quarters = int(input("How many quarters?: "))
dimes = int(input("How many dimes?: "))
nickels = int(input("How many nickels?: "))
pennies = int(input("How many pennies?: "))
money_total = (quarters * .25) + (dimes * .10) + (nickels * .05) + (pennies * .01)
if money_total < MENU[user_choice]['cost']:
print(f"Sorry, not enough money! Here is your change: ${format(money_total, '.2f')}.")
return False
money_profit += MENU[user_choice]['cost']
money_total -= MENU[user_choice]['cost']
print(f"I have enough resources, enjoy your {user_choice}!")
print(f"Here is ${format(money_total, '.2f')} in change.")
return True

# TODO 3. Create user input explaining which coffee you would like to order: "Espresso/Latte/Cappuccino"
coffee_machine = True
while coffee_machine:
user_input = input("What kind of coffee would you like to order? (Espresso/Latte/Cappuccino): ").lower().strip()
if user_input == "report":
report(water, milk, coffee, money_profit)
elif user_input == "off":
coffee_machine = False
print("Goodbye!")
elif user_input in ("espresso", "latte", "cappuccino"):
if check_resources(MENU[user_input]['ingredients']):
# TODO 4. When user selects order, ask user to insert money
total_money = money(user_input)
# TODO 5. Checks to make sure a drink was actually made
if total_money:
for item in MENU[user_input]['ingredients']:
resources[item] -= MENU[user_input]['ingredients'][item]
else:
print("Invalid selection.")

由于某种原因,最初的水、牛奶和咖啡变量是问题所在。还是不明白为什么,我把它们删除了,把报表功能改成了直接调用。它似乎也修复了另一个错误。

from main import MENU, resources
# TODO 1. Create a report of how much water, milk, coffee, and money you have used
def report(water_ingredient, milk_ingredient, coffee_ingredient, money_in_box):
print("The coffee machine has:")
print(f"Water: {water_ingredient}ml")
print(f"Milk: {milk_ingredient}ml")
print(f"Coffee: {coffee_ingredient}g")
print(f"Money: ${format(money_in_box, '.2f')}")

# TODO 2. Check if resources are available for coffee order
def check_resources(ingredients):
for item in ingredients:
if resources[item] < ingredients[item]:
print(f"Sorry, not enough {item}!")
return False
return True

def money(user_choice):
global money_profit
print(f"The cost of {user_choice} is ${format(MENU[user_choice]['cost'], '.2f')}.n Please insert coins: ")
quarters = int(input("How many quarters?: "))
dimes = int(input("How many dimes?: "))
nickels = int(input("How many nickels?: "))
pennies = int(input("How many pennies?: "))
money_total = (quarters * .25) + (dimes * .10) + (nickels * .05) + (pennies * .01)
if money_total < MENU[user_choice]['cost']:
print(f"Sorry, not enough money! Here is your change: ${format(money_total, '.2f')}.")
return False
money_profit += MENU[user_choice]['cost']
money_total -= MENU[user_choice]['cost']
print(f"I have enough resources, enjoy your {user_choice}!")
print(f"Here is ${format(money_total, '.2f')} in change.")
return True

# TODO 3. Create user input explaining which coffee you would like to order: "Espresso/Latte/Cappuccino"
coffee_machine = True
money_profit = 0
while coffee_machine:
user_input = input("What kind of coffee would you like to order? (Espresso/Latte/Cappuccino): ").lower().strip()
if user_input == "report":
report(resources["water"], resources["milk"], resources["coffee"], money_profit)
elif user_input == "off":
coffee_machine = False
print("Goodbye!")
elif user_input in ("espresso", "latte", "cappuccino"):
if check_resources(MENU[user_input]['ingredients']):
# TODO 4. When user selects order, ask user to insert money
total_money = money(user_input)
# TODO 5. Checks to make sure a drink was actually made
if total_money:
for item in MENU[user_input]['ingredients']:
resources[item] -= MENU[user_input]['ingredients'][item]
else:
print("Invalid selection.")

相关内容

  • 没有找到相关文章

最新更新