MENU = {"1": 3.50, "2": 2.50, "3": 4.00, "4": 3.50, "5": 1.75, "6": 1.50, "7": 2.25, "8": 3.75, "9": 1.25}
order = raw_input("Enter a number! ")
menu = list(order) #puts the order into a list (2, 4, 5, 2)
def add_up():
for x in menu:
global items
items = MENU[x]
return items,
total = sum(add_up())
print total
当我运行它时,总打印输出只是列表中的一个值,而不是总和。为什么这不起作用?
答案 0 :(得分:0)
最终add_up()返回字典MENU中的最后一个键,即1.25。
请记住,菜单和菜单在这里并不是指同一件事。一个是字典,另一个是从raw_input返回的字符串。
以下是您可能想要的内容:
def add_up():
total = 0
for x in menu:
total += int(MENU[x])
return total
total = add_up()
print total
您可能也不想同时使用MENU和菜单,因为这会让人感到困惑。
答案 1 :(得分:0)
试试这个:
MENU = {"1": 3.50, "2": 2.50, "3": 4.00, "4": 3.50, "5": 1.75, "6": 1.50, "7": 2.25, "8": 3.75, "9": 1.25}
choices = ['1','2','5','8'] # make sure choices is a list of strings
def add_up():
for x in choices:
# global items # no need for this line
items = MENU[x]
yield items # use yield
total = sum(add_up())
print total
答案 2 :(得分:0)
print(sum([ MENU.get(x, 0) for x in order ]))