Python练习_购物车_day6
2024-09-01 14:22:51
第一次代码
(1) 输出商品列表,用户输入序号,显示用户选中的商品.
页面显示 序号 + 商品名称,如:
1 手机
2 电脑
(2): 用户输入选择的商品序号,然后打印商品名称
(3):如果用户输入的商品序号有误,则提示输入有误,并重新输入。
(4):用户输入Q或者q,退出程序。
flag = True
while flag:
li = ['手机', '电脑', '鼠标垫', '游艇']
for i in li:
print('{}\t{}'.format(li.index(i) + 1, i))
num_of_choose = input('请输入选择的商品序号(按Q退出,不区分大小写):')
if num_of_choose.isdigit():
num_of_choose = int(num_of_choose)
if num_of_choose > 0 and num_of_choose <= len(li):
print(li[num_of_choose - 1])
else:print('请输入有效数字!')
elif num_of_choose.upper() == 'Q':
flag = False
else:
print('请输入整数!')
升级
功能要求:
要求用户输入总资产,例如:2000
显示商品列表,让用户根据序号选择商品,加入购物车购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998}
]
total = 0
flag = True
money = input('请输入您的总资产:')
while flag:
for i in goods:
print('{}\t{}\t{}'.format(goods.index(i) + 1, i['name'], i['price']))
num_of_choose = input('请选择商品的序号(按Q退出,不区分大小写):')
if num_of_choose.isdigit():
num_of_choose = int(num_of_choose)
if num_of_choose > 0 and num_of_choose <= len(goods):
total = total + goods[num_of_choose - 1]['price']
if total < int(money):
print('成功加入购物车!')
print('你当前选择的商品为:{}\t价格为:{}'.format(goods[num_of_choose - 1]['name'],goods[num_of_choose - 1]['price']))
print('总价为:{}'.format(total))
else:
print('账户余额不足!')
flag = False
else:print('请输入有效数字!')
elif num_of_choose.upper() == 'Q':
flag = False
else:print('请输入整数!')
最终
# 把货物放在货架上
li = [
{'name':'苹果', 'price':1},
{'name':'香蕉', 'price':1},
{'name':'西瓜', 'price':10},
{'name':'橘子', 'price':0.5},
]
shopping_car = {} # 建立一个空购物车
print('欢迎光临水果店')
money = input('让我看看你有多少钱:')
if money.isdigit() and int(money) > 0:
while 1:
for i,k in enumerate(li):
print('序号:{}\t商品:{}\t价格:{}'.format(i, k['name'], k['price']))
choose = input('请输入您要购买的商品序号:')
if choose.isdigit() and int(choose) < len(li):
num = input('您要购买的商品数量:')
if num.isdigit():
if int(money) > li[int(choose)]['price'] * int(num):
money = int(money) - li[int(choose)]['price'] * int(num)
if li[int(choose)]['name'] in shopping_car:
shopping_car[li[int(choose)]['name']] += int(num) # 若商品已经在购物车中, 则增加数量
else:
shopping_car[li[int(choose)]['name']] = int(num)
print('购物车中的商品有:{}\t\t您的余额为:{}'.format(shopping_car,money))
else:
print('余额不足')
break
else:
print('您输入的序号有误')
最新文章
- hdu4642 Fliping game ——博弈
- UVALive 5029
- CodeForces 705A Hulk (水题)
- oracle执行带输入输入参数的存储过程
- SharePoint Framework (SPFx)安装配置以及开发-基础篇
- ajax使用json
- NodeJS Stream 四:Writable
- Java的string学习笔记 与char数组和bufferstring的比较
- python下实现二叉堆以及堆排序
- SQL Server使用sp_spaceused查看表记录存在不准确的情况
- springboot使用@data注解,减少不必要代码
- db2 reorgchk
- Spark之GraphX的Graph_scala学习
- KMP模板(KMP)
- 腾讯云JavaWeb环境配置
- android 线程中断的处理
- 【JAVA】抽象类,抽象方法
- PHP函数register_shutdown_function的使用示例
- HDU 5117 Fluorescent (数学+状压DP)
- python终端计算器,还有没其他方法?