首页 > 解决方案 > 为了让三明治机问题更有效,我应该做些什么改变?

问题描述

问题陈述要求我编写一个程序,使用 PyInputPlus 询问用户的三明治偏好。使用 inputMenu 获取面包、蛋白质信息。InputYesNo 用于奶酪浇头和 inputInt 以获得三明治的数量。最后根据所有选择计算三明治的成本。拿出你自己的价格。我怎样才能改进我的程序。该程序有效,但仅适用于 1 种奶酪和 1 种浇头。我应该进行哪些更改以使程序计算多个奶酪和浇头的总数。

import pyinputplus as pypi 

prices = {'Bread':{'Wheat':2, 'White':2, 'Sourdough':3},
          'Protein':{'Chicken':2, 'Turkey':3, 'Ham':3, 'Tofu':2},
          'Cheese':{'Cheddar':1, 'Swiss':1, 'Mozzerella':1},
          'Topping':{'Mayo':0, 'Mustard':0,'Lettuce':1, 'Tomato':1}}
totalPrice = []
bread = pypi.inputMenu(['Wheat','White','Sourdough'],prompt="What kind of Bread would you like?\n",default=None, caseSensitive=False)
breadPrice = prices['Bread'][bread]
totalPrice = breadPrice
protien = pypi.inputMenu(['Chicken', 'Turkey','Ham','Tofu'],prompt="What kind of protein would you like?\n",default=None, caseSensitive=False)
totalPrice += prices['Protein'][protien]
cheese = pypi.inputYesNo("Do you want cheese? Yes/No:\n ", yesVal="yes", noVal="no", caseSensitive=False, default=None, blank=False,)
if cheese == 'yes':
    kindofcheese = pypi.inputMenu(['Cheddar', 'Swiss', 'Mozzerella'],prompt="What kind of cheese would you like?\n",default=None, caseSensitive=False)
    totalPrice += prices['Cheese'][kindofcheese]
else:
    print('No cheese selected')

topping = pypi.inputYesNo("Do you want any toppings? Yes/No:\n", yesVal="yes", noVal="no", caseSensitive=False, default=None, blank=False)
if topping == 'yes':
    kindoftopping=pypi.inputMenu(['Mayo', 'Mustard','Tomato','Lettuce'], prompt="What kind of topping would you like?\n",default=None,caseSensitive=False)
    totalPrice+=prices['Topping'][kindoftopping]
else:
    print('No topping selected')

Qty = pypi.inputInt(prompt="How many sandwiches would you like?\n", default=1, blank=False,min=1, lessThan=5)
totalPrice = totalPrice*Qty
print(f"The total amount payable for your sandwich(es) is {totalPrice}")

标签: python

解决方案


您可以使用 while 循环添加奶酪/浇头,直到用户输入否。这是奶酪的代码,请相应地修改浇头的代码。

cheese = 'yes'  # initialize to get the loop running
while cheese == 'yes':  # ask for (additional) cheese until they enter no
    cheese = pypi.inputYesNo("Do you want cheese? Yes/No:\n ", yesVal="yes", noVal="no", caseSensitive=False, default=None, blank=False,)
    if cheese == 'yes':
        kindofcheese = pypi.inputMenu(['Cheddar', 'Swiss', 'Mozzerella'],prompt="What kind of cheese would you like?\n",default=None, caseSensitive=False)
        totalPrice += prices['Cheese'][kindofcheese]
    else:
        print('No (more) cheese selected')  # slightly modified status text

推荐阅读