首页 > 解决方案 > 披萨店功能中的循环问题

问题描述

我目前正在尝试解决有关披萨店的编码问题。它意味着接受多个参数(范围从 1 到大于 1)并将每个参数的恒定成本相加以返回一定的成本。我的问题是,当前代码无法遍历数据有什么问题。我制作了一个函数、一个字典和一个 for 循环来遍历数据。所有这些都是用 Python 编码的。

def cost_calculator(*x, wings, drinks, coupon):

total_cost = 0  #variable that holds final cost of order
print(total_cost)

pizza_to_price = {"mypizza":13}
drinks_to_price = {"small": 2.00, "medium": 3.00,"large": 3.50,"tub": 3.75}
wings_to_price = {10:5.00, 20:9.00, 40:17.50, 100:48.00}
toppings_to_price = {"pepperoni":1.00, "mushroom":0.50, "olive":0.50, "anchovy":2.00,"ham":1.50}

for pizza in x:
    total_cost += 13.00
for topping in wings:
    total_cost += wings_to_price[topping]
for size in drinks:
    total_cost += drinks_to_price[size]
for discount in coupon:
    total_cost = total_cost - (total_cost * coupon)
total_cost *= 1.0625

round(total_cost,2)
return total_cost

回复:我得到的错误是,如果我取消注释所有内容,则会返回一个 NoneType 值。

我得到的错误

标签: pythonalgorithmfunctionloopsdictionary

解决方案


我不知道这是否是一个错字,但你忘记了缩进:

def cost_calculator(*x, wings, drinks, coupon):

    total_cost = 0.0  #variable that holds final cost of order
    

    pizza_to_price = {"mypizza":13}
    drinks_to_price = {"small": 2.00, "medium": 3.00,"large": 3.50,"tub": 3.75}
    wings_to_price = {10:5.00, 20:9.00, 40:17.50, 100:48.00}
    toppings_to_price = {"pepperoni":1.00, "mushroom":0.50, "olive":0.50, "anchovy":2.00,"ham":1.50}

    for pizza in x:
        total_cost += 13.00
    for topping in wings:
        total_cost += wings_to_price[topping]
    for size in drinks:
        total_cost += drinks_to_price[size]
    for discount in coupon:
        total_cost = total_cost - (total_cost * float(discount))
    total_cost *= 1.0625

    round(total_cost,2)
    return total_cost

pizzas = 3
wings = [10, 20]
drinks = []
discounts = [1.5, 2]
print(cost_calculator(pizzas, wings = wings, drinks = drinks, coupon = discounts))

结果:14.34375

Python函数:https ://www.w3schools.com/python/python_functions.asp

Python 地图:https ://www.geeksforgeeks.org/python-map-function/


推荐阅读