python系统学习:第二周之购物车功能

# 小程序:购物车
'''
1.启动程序后,让用户输入工资,然后打印商品列表
2.允许用户根据商品编号购买商品
3.用户选择商品之后,监测余额是否够,够直接扣款,不够提醒
4.可随时退出,并打印已购商品和余额
'''
# 理清逻辑:输入工资 打印列表 选择商品 购买

# 定义商品列表
shoplists = [('西瓜', 100), ('黄瓜', 200), ('南瓜', 300), ('甜瓜', 1000)]
# 定义参数:用户工资
salary = input('请输入会员卡余额(整数):')
# 定义购物车列表
shop_car = []
# 打印商品列表,打印之前判断用户输入是否为数字
if salary.isdigit():
# 将字符串变成整数型
salary = int(salary)
# 利用for循环和enumerate方法输出列表值和索引
for index, item in enumerate(shoplists):
print(index, item)
# 进入循环(多次购买)
# 提示用户输入购买商品
while True:
shop = input('请输入你想要的商品编号:')
# 判断输入的商品列表是否合法,是否为推出键
if shop.isdigit():
shop = int(shop)
# 判定所选商品在列表范围内
if shop >= 0 and shop < len(shoplists):
# 定义参数承装选中商品
shop_detail = shoplists[shop]
# 判断余额是否充足
if salary >= shop_detail[1]:
salary -= shop_detail[1]
shop_car.append(shop_detail)
print('{0}已经添加至购物车!余额:33[31;1m{1}33[0m ¥'.format(shop_detail[0], salary))
else:
print('余额不足!')
else:
print('没有此商品!')
elif shop == 'q':
print('------购买清单-----')
for index, item in enumerate(shop_car):
print(index, item)
print('余额:33[31;1m{0}33[0m ¥'.format(salary))
break
else:
print('请输入正确的商品编号!')
else:
print('请输入数字!')

/* 喜欢的同学加我博客一起讨论*/
原文地址:https://www.cnblogs.com/niushichong/p/9871195.html