首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Python第2版自动化无聊的东西-三明治制造者实践项目

用Python第2版自动化无聊的东西-三明治制造者实践项目
EN

Code Review用户
提问于 2020-11-10 13:59:43
回答 1查看 1.5K关注 0票数 5

我正在学习过程中,虽然这是一个非常容易的项目,我仍然希望专家们能回顾它并分享所能做的改进,如果有人想使用其他模块来缩短代码,那么您也可以使用它们,我已经感谢那些想为此花费宝贵时间的人。其他初学者也会发现这很有帮助。

代码语言:javascript
复制
import pyinputplus as pyp


menu = True

# price of all ingredients
prices = {'wheat': 2, 'white': 1, 'sour dough': 3, 'chicken': 2, 'turkey': 3, 'ham': 2, 'tofu': 1,
          'cheddar': 1, 'swiss': 2, 'mozzarella': 3, 'mayo': 1, 'mustard': 1, 'lettuce': 1,
          'ketchup': 1}
while menu:
    # options to select bread, protein, cheese with inputMenu() method
    bread = pyp.inputMenu(['wheat', 'white', 'sour dough'],
                          prompt='Please select the type of bread you want for your sandwich: \n',
                          numbered=True)

    protein = pyp.inputMenu(['chicken', 'Turkey', 'Ham', 'Tofu'],
                            prompt='Which type of protein you would like: \n',
                            numbered=True)

    cheese = pyp.inputYesNo('Do you want Cheese in your sandwich?(Y/N)\n')
    cheese_type = ''
    if cheese == 'yes':
        cheese_type = pyp.inputMenu(['cheddar', 'swiss', 'mozzarella'], numbered=True)

    # using inputYesNo() for single ingredients with no further types
    mayo = pyp.inputYesNo('Do you want mayo?(Y/N) \n')
    mustard = pyp.inputYesNo('Do you want mustard?(Y/N) \n')
    lettuce = pyp.inputYesNo('Do you want lettuce?(Y/N) \n')
    ketchup = pyp.inputYesNo('Do you want tomato ketchup?(Y/N) \n')

    # using inputInt() and blockRegexes that do not allow negative integer, float or 0
    sandwichQT = pyp.inputInt('How much sandwiches you would like to order?\n',
                              blockRegexes=['[0|-|.]'])

    total_amount = 0

    # using for loop to print items, prices and adding their amount to total_amount variable
    for item, price in prices.items():
        if bread == item:
            print(f'Your sandwich ingredients and prices are as follows: \n'
                  f'{item}= {price}')
            total_amount += price

        if protein == item:
            print(f'{item}= {price}')
            total_amount += price

        if cheese_type == item:
            print(f'{item}= {price}')
            total_amount += price

    # for items that have yes and no values stored and also adding their amount to total
    if mayo == 'yes':
        print(f"mayo = {prices['mayo']}")
        total_amount += prices['mayo']

    if mustard == 'yes':
        print(f"mustard = {prices['mustard']}")
        total_amount += prices['mustard']

    if lettuce == 'yes':
        print(f"lettuce = {prices['lettuce']}")
        total_amount += prices['lettuce']

    if ketchup == 'yes':
        print(f"ketchup = {prices['ketchup']}")
        total_amount += prices['ketchup']

    # at the end printing total amount and how much sandwiches have been ordered
    print(f"sandwich cost x sandwich Qt ordered = {total_amount}x{sandwichQT} = "
          f"{total_amount*sandwichQT}")

    # confirming if the user need to reorder or user wants to confirm the order by simple yes/no
    # if user confirm by typing yes or y then menu will become false and while loop will terminate
    order_confirm = pyp.inputYesNo('Please confirm your order: (Y/N)\n')
    if order_confirm == 'yes':
        print('Please take your order number from the machine and you will be notified when '
              'its ready')
        menu = False
EN

回答 1

Code Review用户

回答已采纳

发布于 2020-11-10 15:02:56

while True

首先,在Python中使用“标志”变量并不常见。与使用布尔变量控制while循环不同,您只需执行while True: ... break

避免多ifs

您可能会注意到以下内容的重复结构:

代码语言:javascript
复制
print(f'{item}= {price}')
total_amount += price

在每个if下。这是因为你的逻辑颠倒了。您目前正在迭代所有可能的成分,并检查是否需要它们。但可能有许多没有使用的。更有意义的是,创建一个在使用的成分清单,然后只是把他们的价格在一个循环。这需要改变你保存酱汁的方式。我们将不将它们保存为'yes',而是使用它们的名称来保存它们--以便与prices切分键匹配。

因此,我们将创建一个ingredients列表,并添加酱汁:

代码语言:javascript
复制
if pyp.inputYesNo('Do you want mayo?(Y/N) \n') == 'yes':
    ingredients.append('mayo')

现在,打印循环将是if-free:

代码语言:javascript
复制
print(f'Your sandwich ingredients and prices are as follows: \n')
for item in ingredients:
    price = prices[item]
    print(f'{item}= {price}')
    total_amount += price

全码

代码语言:javascript
复制
import pyinputplus as pyp

# price of all ingredients
prices = {'wheat': 2, 'white': 1, 'sour dough': 3, 'chicken': 2, 'turkey': 3, 'ham': 2, 'tofu': 1,
          'cheddar': 1, 'swiss': 2, 'mozzarella': 3, 'mayo': 1, 'mustard': 1, 'lettuce': 1,
          'ketchup': 1}

while True:
    ingredients = []
    # options to select bread, protein, cheese with inputMenu() method
    ingredients.append(pyp.inputMenu(['wheat', 'white', 'sour dough'],
                          prompt='Please select the type of bread you want for your sandwich: \n',
                          numbered=True))

    ingredients.append(pyp.inputMenu(['chicken', 'Turkey', 'Ham', 'Tofu'],
                            prompt='Which type of protein you would like: \n',
                            numbered=True))

    if pyp.inputYesNo('Do you want Cheese in your sandwich?(Y/N)\n')== 'yes':
        ingredients.append(pyp.inputMenu(['cheddar', 'swiss', 'mozzarella'], numbered=True))

    # using inputYesNo() for single ingredients with no further types
    if pyp.inputYesNo('Do you want mayo?(Y/N) \n') == 'yes':
        ingredients.append('mayo')
    if pyp.inputYesNo('Do you want mustard?(Y/N) \n') == 'yes':
        ingredients.append('mustard')
    if pyp.inputYesNo('Do you want lettuce?(Y/N) \n') == 'yes':
        ingredients.append('lettuce')
    if pyp.inputYesNo('Do you want tomato ketchup?(Y/N) \n') == 'yes':
        ingredients.append('ketchup')

    # using inputInt() and blockRegexes that do not allow negative integer, float or 0
    sandwichQT = pyp.inputInt('How much sandwiches you would like to order?\n',
                              blockRegexes=['[0|-|.]'])

    total_amount = 0
    # using for loop to print items, prices and adding their amount to total_amount variable
    print(f'Your sandwich ingredients and prices are as follows: \n')
    for item in ingredients:
        price = prices[item]
        print(f'{item}= {price}')
        total_amount += price

    # at the end printing total amount and how much sandwiches have been ordered
    print(f"sandwich cost x sandwich Qt ordered = {total_amount}x{sandwichQT} = "
          f"{total_amount*sandwichQT}")

    # confirming if the user need to reorder or user wants to confirm the order by simple yes/no
    # if user confirm by typing yes or y then menu will become false and while loop will terminate
    if pyp.inputYesNo('Please confirm your order: (Y/N)\n')== 'yes':
        print('Please take your order number from the machine and you will be notified when '
              'its ready')
        break
票数 5
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/251902

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档