python实际练习1——简单购物车

时间:2023-03-10 04:29:38
python实际练习1——简单购物车

要求实现

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
  4. 可随时退出,退出时,打印已购买商品和余额

自己写的代码是

#Author:Wildwolf
#-*- coding:utf-8 -*- #可以用index确定下标
#本例中是静态的,用list固定了产品种类,没有想到用下标的形式选择商品
#自己增加了可选择购买物品数量的功能 import sys alterlist = ['欢迎光临', [1, 'MG元祖高达', 150], [2,'MG独角兽一号机', 230], [3, 'MG报丧女妖', 220], [4, 'MG沙扎比', 430],
[5, 'MG精神力感知扎古', 420], [6, 'MG红异端', 255]]
shoplist = []
list = ['', '', '', '', '', '']
salary = input("请输入您的工资:")
while True:
salarylast = salary
for i in alterlist:
print(i)
print('如果您想退出,请输入"q"或按任意键继续')
getpass = input()
while getpass == 'q':
print("您所购商品为:-----shopping list-----")
for i in shoplist:
print(i)
print("您的余额为:\033[31;1m%s\033[0m" % salarylast)
print("谢谢惠顾!")
sys.exit(0)
else:
print("请按提示输入:")
getpass2 = input("请输入您要购买的商品编号:")
if getpass2 not in list:
print("输入错误,请重新输入")
continue
else:
select = int(getpass2)
if select > 6:
print("没有对应的商品,请重新输入:")
else:
if int(salary) > int(alterlist[select][2]):
number = input("请输入您要购买的数量:")
if number not in list:
print("输入错误,请重新输入")
else:
salary = (int(salary) - int(alterlist[select][2])*int(number))
shoplist.append([alterlist[select], number])
print("商品已放入购物车,您的余额为\033[31;1m%s\033[0m" % salary)
else:
print("您的余额不足")

从视频里学到的高级一点的代码为

#-*- coding:utf-8 -*-

print("欢迎光临!")
alter_list = [('MG元祖高达', 150),
('MG独角兽一号机', 230),
('MG报丧女妖', 220),
('MG沙扎比', 430),
('MG精神力感知扎古', 420),
('MG红异端', 255)]
shoplist = [] salary = input("输入你的工资:")
if salary.isdigit(): #判断是否字符串是否由数字构成
salary = int(salary) #转换成整数类型
while True:
for index, item in enumerate(alter_list): #print(product_list.index(item),item)
print(index, item)
user_choice = input("请输入您要购买的商品编号:")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(alter_list) and user_choice >=0: #列表的长度
p_item = alter_list[user_choice]
if p_item[1] <= salary:
alter_list.append(p_item)
salary -= p_item[1]
print("将 %s 添加至您的购物车,您的余额为 \033[31;1m%s\033[0m" % (p_item, salary))
else:
print("\033[41;1m你的余额为[%s]\033[0m" % salary) #输出余额
else:
print("商品编号 [%s] 不存在!" % user_choice)
elif user_choice == 'q':
print("--------shopping list------")
for p in alter_list:
print(p)
print("您的余额为:", salary)
print("谢谢惠顾!")
exit()
else:
print("输入错误")

还能有更高级的功能,随着学习深入添加