底部的汉堡包的值不会乘以输入值菜单的次数。计数仅给我两个答案,它们不能正确输入实际的时间(菜单)。
def input1():
menu = input("""
hamburger--: """)
loop = input("Would you like to add another Food: (y/n)?")
return menu, loop
def calc(menu, loop):
hamburger = 1.25
count = 1
if menu == "h":
print(loop)
if loop == "y":
menu, loop =input1()
calc(menu, loop)
if loop == "n":
menu = (count)
menu = int(count)
print(menu * 1.25)
count+=1
def main():
menu, loop =input1()
calc(menu, loop)
答案 0 :(得分:0)
在递归调用中,您要添加每个值
<current value> + calc() + calc()....
赞:
def input1():
menu = input("""
hamburger--: """)
loop = input("Would you like to add another Food: (y/n)?")
return menu, loop
def calc():
# Get current value
menu, loop = input1()
cost = 0
if 'h' == menu:
cost = 1.25
# Example other items
elif 'f' == menu: # Fries
cost = .75
# Make recursive calls, if needed
if loop == "y":
cost += calc()
# Return the total (so far)
return cost
def main():
print(calc())
或者您可以将所有菜单项放在字典中:
full_menu = {'h': 1.25, 'f': .75, 's': 1.0}
def calc():
menu, loop = input1()
cost = 0
if menu in full_menu:
cost = full_menu[menu]
if loop == "y":
cost += calc()
return cost
答案 1 :(得分:0)
我认为(如果我正确理解了问题),问题在于您仅在最后一次迭代中执行“ count + = 1”。 想象一下你这样做了两次
因为if循环==“ n”仅在您不想添加项目时发生。
以下是我认为coulf是更好的解决方案的建议:
PRICES = {
'hamburger': 1.25
}
def get_input():
menu_item = input('Item')
loop = input("Would you like to add another Food: (y/n)?")
return menu_item, loop
def calc():
# Start a item count
item_count = {
'hamburguer': 0
}
finished = False
while not finished:
menu_item, loop = get_input()
# Check if item in menu
if menu_item in PRICES.keys():
item_count[menu_item] += 1
else:
print('Sorry, the item is not in the menue')
# Check if no more items are expected
if loop == "n"
finished = True
return sum([ PRICES[item] * ammount (item, ammount) in item_count.values()])
def main():
pritn(calc())
在函数中定义常量(如汉堡包价格)被认为是不好的做法。 另外,覆盖参数(如菜单)可能会造成混淆。
我可能没有正确理解这个问题。但我希望这对您有帮助。 不要犹豫,纠正我,对不起,英语不好