python商品购物结算循环
时间: 2024-03-31 15:31:09 浏览: 26
在Python中,可以使用循环来实现商品购物结算的功能。以下是一个简单的示例代码:
```python
# 初始化购物车和总金额
shopping_cart = []
total_amount = 0
while True:
# 输入商品信息
name = input("请输入商品名称(输入exit退出):")
if name == "exit":
break
price = float(input("请输入商品价格:"))
quantity = int(input("请输入商品数量:"))
# 计算小计金额
subtotal = price * quantity
# 将商品信息添加到购物车
shopping_cart.append({"name": name, "price": price, "quantity": quantity, "subtotal": subtotal})
# 更新总金额
total_amount += subtotal
# 打印购物清单
print("购物清单:")
for item in shopping_cart:
print(f"商品名称:{item['name']},单价:{item['price']},数量:{item['quantity']},小计:{item['subtotal']}")
# 打印总金额
print(f"总金额:{total_amount}")
```
这段代码使用了一个无限循环 `while True`,通过输入商品信息来添加商品到购物车,直到输入"exit"退出循环。在循环内部,计算每个商品的小计金额,并将商品信息以字典的形式添加到购物车列表中。最后,通过遍历购物车列表打印出购物清单,并计算并打印出总金额。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)