Python 简易购物车代码实现

#定义商品和价格
products = {'apple': 5, 'banana': 3, 'orange': 4, 'grape': 6, 'watermelon': 10}

#初始化购物车
cart = {}

#打印商品清单
print('商品清单:')
for product, price in products.items():
    print(product, ':', price)

#循环加入购物车
while True:
    choice = input('请输入要加入购物车的商品名称(按q结算):')
    if choice == 'q':
        break
    elif choice in products:
        if choice in cart:
            cart[choice] += 1
        else:
            cart[choice] = 1
        print(choice, '已加入购物车。')
    else:
        print('没有这个商品,请重新输入。')

#打印购物清单
print('购物清单:')
total_price = 0
for product, quantity in cart.items():
    price = products[product] * quantity
    total_price += price
    print(product, ':', quantity, '*', products[product], '=', price)

#打印总价
print('总价为:', total_price)

这个购物车程序很简单,但涵盖了购物车的基本功能:显示商品清单、加入购物车、打印购物清单、计算总价。您可以根据需要进行扩展和改进。

Python 简易购物车代码实现

原文地址: https://www.cveoy.top/t/topic/lUQd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录