python购物车程序2019_Python——购物车程序(列表的应
⽤)
购物车基本功能:
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:
unt(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: #将加⼊购物车中的商品进⾏分类计数、展⽰
unt(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.')
运⾏结果如下:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。