python购物车结算不了_Python——购物车问题

product_list=[('Mac',9000),

('kindle',800),

('tesla',900000),

('book',50),

('bike',2000)]

money=input('please input your money:')#输入本金

shopping_car=[]

if money.isdigit():#saving是个字符串,字符串里面是数字

money=int(money)

#将商品展示给用户

#for i in product_list:

# print(product_list.index(i)+1,i)

#for i in enumerate(product_list,1):

# print(i)

while True:

for i,v in enumerate(product_list,1):

print(i, v)

choice=input('选择购买商品编号[退出:q]:')

if choice.isdigit():

choice=int(choice)

if choice>0 and choice<=len(product_list):

p_item=product_list[choice-1]

if p_item[1]

money-=p_item[1]

shopping_car.append(p_item)

else:

print('余额不足,还剩%s'%money)

print(p_item)

else:

print('编号不存在')

elif choice=='q':

print('--------------您已经购买如下商品--------------')

for i in shopping_car:

print(i)

print('您的余额为%s'%money)

break

else:

print('invalid input')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中实现一个简单的购物车结算功能,通常涉及到以下几个步骤: 1. **创建商品类**:定义一个商品类(例如`Product`),包含属性如名称、价格、数量等。 ```python class Product: def __init__(self, name, price): self.name = name self.price = price self.quantity = 0 def set_quantity(self, quantity): self.quantity = quantity def get_total_cost(self): return self.price * self.quantity ``` 2. **购物车类**:创建一个购物车类(例如` ShoppingCart`),用于存储商品和处理结算。 ```python class ShoppingCart: def __init__(self): self.items = [] def add_item(self, product, quantity=1): item = product item.set_quantity(quantity) self.items.append(item) def remove_item(self, product_name, quantity=None): for item in self.items: if item.name == product_name: if quantity is not None: item.set_quantity(item.quantity - quantity) else: self.items.remove(item) break def total_cost(self): return sum(item.get_total_cost() for item in self.items) ``` 3. **使用示例**: ```python # 创建商品实例 apple = Product("Apple", 1.5) banana = Product("Banana", 0.5) # 添加商品到购物车 cart = ShoppingCart() cart.add_item(apple, 3) cart.add_item(banana, 2) # 结算 print(f"Total cost: {cart.total_cost():.2f}") # 删除商品 cart.remove_item("Apple", 1) print(f"New total cost after removing an apple: {cart.total_cost():.2f}") ``` 这个例子中,购物车可以添加商品,查询总成本,以及删除特定商品。你可以根据需求扩展购物车的功能,比如计算优惠后的总价、查看购物车内容等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值