python实现购物简单流程需求:
  1.启动程序后,让⽤户输⼊⼯资,然后打印商品列表
  2.允许⽤户根据商品编号购买商品
  3.⽤户选择商品后,检测余额时候够,够就直接扣款,不够就提醒
  4.可随时退出,退出时,打印已购买商品和余额
python环境:3.6.5
知识点:if-else,for,while
代码:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author:coding2018
'''
需求:
1.启动程序后,让⽤户输⼊⼯资,然后打印商品列表
2.允许⽤户根据商品编号购买商品
3.⽤户选择商品后,检测余额时候够,够就直接扣款,不够就提醒
3.可随时退出,退出时,打印已购买商品和余额
'''
#商品列表
product_list = [
('iPhone',5800),
('Mac Pro',9800),
('Bike',800),
('Watch',10600),
('Coffee',31),
('Ales Python',120)
]
#购物车
shopping_list = []
#输⼊⼯资
salary = input("Input your salary:")
#isdigit() ⽅法检测字符串是否只由数字组成。
if salary.isdigit():
#salary转换成int型
salary = int(salary)
#循环
while True:
#取product_list中商品下标和商品
#enumerate() 函数⽤于将⼀个可遍历的数据对象(如列表、元组或字符串)
html实现用户注册登录代码
# 组合为⼀个索引序列,同时列出数据和数据下标,⼀般⽤在 for 循环当中
for index,item in enumerate(product_list):
print(index,item)
print("q 退出")
# for item in product_list:
#    print(product_list.index(item),item)
#输⼊表购买商品的标号
user_choice = input("选择要买的商品编号>>>:")
if user_choice.isdigit():
user_choice = int(user_choice)
#判断输⼊编号
if user_choice < len(product_list) and user_choice >= 0:
p_item = product_list[user_choice]
#判断商品价格是否⼩于余额
if p_item[1] <= salary:  #买的起
#商品加⼊购物车
shopping_list.append(p_item)
#余额减少
salary -= p_item[1]
print("Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m" %(p_item,salary))
else:
print("\033[41;1m你的余额只有[%s],⽆法购买\033[0m" % salary)
else:
print("product code [%s] is not exist!" % user_choice)
elif user_choice == 'q':
print('--------------shopping list---------------')
for p in shopping_list:
print(p)
print("Your current balance:",salary)
exit()
else:
print("invalid option") else:
print("该输⼊不是只由数字组成")

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