pyhton购物程序

时间:2023-03-09 04:04:17
pyhton购物程序

要求:

  1. 启动程序后,让用户输入工资,然后打印出带有序号的商品列表
  2. 用户输入商品序号购买相应的商品,或者输入 ' q ' 退出购买界面
  3. 选择商品后,检查余额是否足够,够则直接扣款,不够则提示余额不足
  4. 用户每购买一件商品后,或者输入 ' q ' 退出购买界面后,提示:是否继续购买?(Y/N),实现多次购买
  5. 若用户购买了商品,打印出购买的商品列表,总金额,余额;若用户没买任何商品,打印:交易结束,购物失败

Readme:

  运行程序,输入薪水,根据商品列表的序号选择购买的商品,可以选择多次购买,或者不购买

流程图:

    pyhton购物程序    

代码:

 # 简单的购物小程序

 product_list = [
['surface pro 4', 7800],
['dell xps 15', 12000],
['macbook', 12000],
['小米6', 2499],
['iphone7', 4600],
['坚果Pro', 1499]
]
shopping_list = [] # 判断输入的薪水格式是否正确
while True:
salary = input('\n请输入您的薪水:')
if not salary.isdigit(): # 薪水不是数字,结束循环
print('\n输入格式有误!请重新输入...')
continue
break balance = salary = int(salary) print('\n-----------欢迎购买------------\n') # 生成带序号的商品列表
for index, item in enumerate(product_list):
print(index, item) # 判断输入的序号是否符合要求
while True: while True:
i = input('\n输入您要购买的商品序号,或输入 q 取消购买:')
if i == 'q': # 输入 q 退出购买界面
while True:
a = input('\n是否继续购买?(Y/N):')
if a != 'n' and a != 'N' and a != 'y' and a != 'Y':
print('\n输入格式有误,请重试...')
continue
elif a == 'y' or a == 'Y': # 继续购买
break
else: # 购买完毕
if balance == salary: # 没有买任何东西
print('\n交易结束,购买失败...')
exit()
else: # 结算
print('\n您已成功购买以下商品:\n')
for item in shopping_list:
print(item)
print('\n共消费金额 %d 元,余额 %d 元' % (salary - balance, balance))
exit()
continue if not i.isdigit(): # 序号不是数字,结束循环
print('\n输入格式有误!请重新输入...')
continue i = int(i) if i < 0 or i >= len(product_list): # 序号范围不正确,结束循环
print('\n此商品不存在,请重新输入...')
continue
break product = product_list[i]
price = int(product[1]) # 判断余额是否充足,够就直接扣款,不够提醒
if price <= balance:
balance -= price
shopping_list.append(product_list[i])
print('\n您已成功购买 %s ,当前余额为 %d 元' %(product, balance))
else:
print('\n购买失败,您的余额不足...') while True:
a = input('\n是否继续购买?(Y/N):')
if a != 'n' and a != 'N' and a != 'y' and a != 'Y':
print('\n输入格式有误,请重试...')
continue
break if a == 'Y' or a == 'y':
continue
else:
break if balance == salary:
print('\n交易结束,购买失败...')
exit()
else:
print('\n您已成功购买以下商品:\n')
for item in shopping_list:
print(item)
print('\n共消费金额 %d 元,余额 %d 元' %(salary-balance, balance))
exit()