我正在为一个函数编写代码,想要转换此输入,
[], [], ["pepperoni", "pepperoni"], wings=[10, 20], drinks=["small"]
在函数cost_calculator
中问题是它不是让我接受它,因为它里面有翅膀和饮料这个词。试图将其转换为列表会给我错误的语法。我也无法从输入中取出翅膀和饮料这两个词。我的代码:
def cost_calculator(x):
cost=0
drinks={"small":2.00,"medium":3.00,"large":3.50,"tub":3.75}
wings={10:5.00,20:9.00,40:17.50,100:48.00}
toppings={"pepperoni":1.00,"mushroom":0.50,"olive":0.50,"anchovy":2.00, "ham":1.50}
pizza={[]:13.00}
for i in x:
if i in pizza:
cost=cost+pizza[i]
elif i in toppings:
cost=cost+toppings[i]
elif i in drinks:
cost=cost+drinks[i]
elif i in wings:
cost=cost+wings[i]
else:
break
return cost
输入时
cost_calculator([], [], ["pepperoni", "pepperoni"], wings=[10, 20], drinks=["small"])
它给了我
cost_calculator() got an unexpected keyword argument 'wings'
我需要使用[]来显示应该制作的披萨的价值
cost=cost+13.00
我怎样才能克服这个
答案 0 :(得分:0)
不完全确定函数的参数是什么,但是如果你想使用关键字args,请使用 **
语法:
所以,我想我明白args是什么(按此顺序):
[]
,每个代表一个披萨因此我们可以使用variable number of args和keyword args:
# Tuple of var args and a dictionary of keyword args
def cost_calculator(*args, **kwargs):
drinks = {"small": 2.00, "medium": 3.00, "large": 3.50, "tub": 3.75}
wings = {10: 5.00, 20: 9.00, 40: 17.50, 100: 48.00}
toppings = {"pepperoni": 1.00, "mushroom": 0.50, "olive": 0.50, "anchovy": 2.00, "ham": 1.50}
cost = 0
coupon_value = 0.0
# args is a tuple of unnamed parameters
for a in args:
# [] has 0 length so it's a pizza
if 0 == len(a):
cost += 13.00
# Otherwise it must be toppings
else:
cost += sum([toppings[x] for x in a if x in toppings])
# Step through the keyword args
for key,value in kwargs.items():
if key == "drinks":
cost += sum([drinks[x] for x in value if x in drinks])
elif key == "wings":
cost += sum([wings[x] for x in value if x in wings])
elif key == "coupon":
coupon_value = value
else:
break
return cost * (1.0 - coupon_value)
c = cost_calculator([], [], ["pepperoni", "pepperoni"], wings=[10,10], drinks=["small"], coupon=0.1)
print(c)