用Python编程打印超市小票
时间: 2024-09-09 13:04:42 浏览: 95
基于Python的超市购物小票随机抽奖程序.zip
在Python中,你可以创建一个简单的函数来模拟打印超市小票。首先,我们可以定义商品列表、价格以及折扣等变量。下面是一个基础的例子:
```python
def print_receipt(items, prices, discounts=None):
total_price = 0
receipt = "\n超市小票\n"
for i, item in enumerate(items):
if discounts and i < len(discounts): # 如果有折扣信息
price_with_discount = prices[i] * (1 - discounts[i])
else:
price_with_discount = prices[i]
total_price += price_with_discount
receipt += f"第{i+1}项: {item}\n价格: {price_with_discount:.2f}元\n---\n"
receipt += f"总计: {total_price:.2f}元\n感谢光临!\n"
print(receipt)
# 示例使用
items = ["苹果", "香蕉", "牛奶"]
prices = [5.00, 3.00, 8.50]
discounts = [0.1, None, 0.05] # 第一项9折,第三项5%
print_receipt(items, prices, discounts)
```
这个例子中,`print_receipt`函数接受商品名称列表、价格列表和可选的折扣列表作为输入。函数会计算每个项目的打折价格,累加总价,并生成包含所有信息的小票。
阅读全文