【问题标题】:Function to write Shop Receipt - Python [closed]编写商店收据的功能 - Python [关闭]
【发布时间】:2022-06-11 01:18:54
【问题描述】:

努力编写一个函数来打印商店的“收银员收据”输出 它应该接受 3 个项目,然后将它们汇总并打印出带有 TOTAL 的详细收据。

def reciept(Item_1_name, Item_2_name, Item_3_name):
    Item_1_price = 50.45
    Item_2_price = 12
    Item_3_price = 80.55
    total = 'Total', Item_1_price + Item_2_price + Item_3_price
    return Item_1_name, Item_1_price, Item_2_name, Item_2_price, Item_3_name, Item_3_price, total
        
    
reciept("Trainers", "T-Shirt", "Boots")

我的答案产生了输出,但不是我正在寻找的格式。这个问题是一个基本问题,但我想我很困惑。谁能帮我理解我哪里出错了?

【问题讨论】:

  • 目前您只需要 3 个常数并将它们相加,但我假设您希望价格取决于输入项。另外,您的预期输出是什么?可以在控制台打印的字符串?
  • 是的,我想确定取决于输入项目的价格。我的预期输出就像上图一样,左边是项目,右边是这些特定项目的价格,最后是总计。

标签: python


【解决方案1】:

这是一个建议。首先,您必须为您的商品定义价格。你可以通过字典来实现它

item_prices = {
    "Trainers": 50.45,
    "T-Shirt": 12,
    "Boots": 80.55,
    # Add any other item here
}

然后,在您的函数中,您必须检索所选商品的价格。这个想法是有一个未定义数量的items,而不是只有 3 个

total_price = sum(item_prices[item] for item in items)

最后,您将构建字符串,使用\n 创建一个新行并使用\t 插入空格。最后,如果您关心将数字放在其他数字的下方,并且您的项目长度非常不同,您可以用空格填充您的字符串。

这里是完整代码(我使用了for 循环来明确计算,但您也可以使用列表推导或其他方法):

item_prices = {
    "Trainers": 50.45,
    "T-Shirt": 12,
    "Boots": 80.55,
    # Add any other item here
}


def receipt(*items):
    # Create our output variables and other useful variables
    total_price = 0
    total_string = "TOTAL"
    output_string = ""
    max_item_length = max(len(item) for item in items) + 5

    # Build our outputs by iterating over items
    for item in items:
        current_item_price = item_prices[item]  # get price
        total_price += current_item_price  # sum to total
        output_string += item + (' ' * (max_item_length - len(item))) + \
            str(current_item_price) + '\n'  # add to output string, ensuring a fixed number of characters before price

    # Add total price, still maintaining a fixed number of chars before price
    output_string += total_string + (' ' * (max_item_length - len(total_string))) + str(total_price)

    return output_string


print(receipt("Trainers", "T-Shirt", "Boots"))

# Prints:
#
# Trainers     50.45
# T-Shirt      12
# Boots        80.55
# TOTAL        143.0

注意*items在这里被用于get an undefinide number of arguments to the input of our function

【讨论】:

  • 非常感谢您的回答和向我解释。
猜你喜欢
  • 2021-02-27
  • 1970-01-01
  • 2017-05-10
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多