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