购物车基本功能:
1.展示购物清单、价格信息。
2.由客户选择商品序号、加入购物车。
3.结束购物后,展示购物车中的商品信息,余额信息。
其他规则:所选商品价格超出当前余额时,提示钱不够;
直到客户输入quit,退出购物;
# !/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# __author__: Ed Frey
# Date: 18/7/24
# 购物车程序
salary = 20000
goods_list = ['iphone6s', 'macbook', 'coffee', 'python book', 'bicycle']
goods_price = [5800, 9000, 32, 80, 1500]
print('-------the list of goods and price------')
for i in goods_list:
print("%d.\t%s\t%d" % (goods_list.index(i) + 1, i, goods_price[goods_list.index(i)]))
print('-' * 40)
bicycle = []
list = ['1', '2', '3', '4', '5']
balance = salary
while True:
select = input("please choose the number of goods(input quit to exit):")
if select in list:
select = int(select) - 1
if balance < goods_price[select]:
print('your balance is not enough,%d' % balance)
else:
bicycle.append(goods_list[select])
balance -= goods_price[select]
print('''%s\t%d
has been put into your bicycle,the current balance is %d
''' % (goods_list[select], int(goods_price[select]), balance))
elif select == 'quit':
print('your purchase list:')
for i in goods_list:
if i in bicycle:
j=bicycle.count(i)
print("%s\t%d\t*%d" % (i, goods_price[goods_list.index(i)],j))
print('\r\nyour balance is %d\r\nYour are welcome!' % balance)
break
else:
print('invalid input! please input again.')
运行结果:
上面的代码,刚学完列表的时候写的,其实存在很多问题:比如商品、价格做到2个列表里,每次索引起来很麻烦,万一不小心价格顺序改一下,大厦直接坍塌,所以要做一个嵌套的列表;另外就是在输出购物清单时,那个来回索引很容易绕晕;还有新函数enumerate生成序号、 .isdigit()判断是否数字的应用。
修改完善后的代码如下:
salary = 20000
goods_list = [
('iphone6s',5800),
('macbook',9000),
('coffee',32),
('python book',80),
('bicycle',1500)]
bicycle = []
balance = salary
while True:
print('-------the list of goods and price------')
for i, v in enumerate(goods_list, 1):# enumerate函数可以加序号,第二个参数是第一个序号初始值,如果为空从0开始。
print(i, '>>>', v)
print('-' * 40)
select = input("please choose the number of goods(input quit to exit):")
if select.isdigit():
select = int(select) - 1
if select in range(len(goods_list)):#len函数的使用,便于商品列表更新,不需要再维护可选商品序号。
if balance < goods_list[select][1]:
print('your balance is not enough,%d' % balance)
else:
bicycle.append(goods_list[select])
balance -= goods_list[select][1]
print('''%s
has been put into your bicycle,the current balance is %d
''' % (goods_list[select], balance))
else:
print('invalid input! please input again.')
elif select == 'quit':
print('————————————————————————————————————————————————————————\r\nyour purchase list:')
for i in goods_list:
if i in bicycle: #将加入购物车中的商品进行分类计数、展示
j=bicycle.count(i)
print("%s\t*%d" % (i,j))
print('\r\nyour balance is %d\r\nYour are welcome!' % balance)
break
else:
print('invalid input! please input again.')
运行结果如下:
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有