python - 披萨店功能中的循环问题
问题描述
我目前正在尝试解决有关披萨店的编码问题。它意味着接受多个参数(范围从 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 值。
解决方案
我不知道这是否是一个错字,但你忘记了缩进:
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/
推荐阅读
- ios - 如何防止单例对象创建?
- javascript - 删除特定键值但在 javascript 中获取所有嵌套数组对象值
- docker - Kubernetes部署yaml中的多个命令
- javascript - 将当前页面 URL 作为隐藏字段提交,同一页面上有多个表单(Javascript)
- reactjs - 从 React Navigation v4 升级到 v5 时获取默认样式
- c# - 如何使用 WinApi 获取嵌套的子句柄并设置它们的值
- vb.net - 如何从另一个表单 vb.net 获取 SelectedIndex
- java - 在 Kotlin 中仅使用 getter 覆盖 Java 接口
- laravel - LARAVEL:一个身份验证守卫的多个驱动程序
- python - 无论什么用户登录,Django 模型外键总是默认的