首先理清思路,怎么实现这个购物车的流程:
1.0 商城的商品,这里要用到LIST与tuple.
2.0 用户输入自己的salary,这里要用到input用户交互
3.0 用户选商品,怎么选,这里是list 的索引值来代码
4.0 判断用户的钱是否够支付,用到IF,如果还有更多的钱,就继续购买,这里用到while
5.0 如果用户不想买了,怎么结束
6.0 购物完成后,显示所购商品与账号余额。
购物车程序练习:
1.0 定义一个商品列表:
#定义一个商品列表: product_list = [ ("Apple Iphone X",6888), ("Dell Notebook",3200), ("Bike",680), ("Mouse",365), ("earphone",1088), ("sunglass",900), ("Paython book",218), ]
2.0 输入的你的salary,并且判断用户输入的是数字,不是其他ABC,如果是数字,用INT方法把输入的值转化为整型:
salary = input("please input your salary:") if salary.isdigit(): salary = int(salary) else: print("please write right salary")
3.0 列出所有商品:
for product_code, i in enumerate(product_list,1):#enumerate遍历一个列表,同时把索引值与列表元素以对应关系, print(product_code,i)
4.0 用户交互,让用户选择产品:
customer_choice = input("please input your love product:(Q is quit)") if customer_choice.isdigit(): customer_choice = int(customer_choice)
5.0 判断用户的钱是否可以支付:
if customer_choice <= len(product_list) and customer_choice > 0: product_choice = product_list[customer_choice-1] if salary >= product_choice[1]: print("you get it") product_cart.append(product_choice) salary -= product_choice[1] else: print("it isn't enough money to shopping,only %s usd" % salary) for product_number, i in enumerate(product_cart): print(product_number, i) break
6.0 所有代码:
#定义一个商品列表: product_list = [ ("Apple Iphone X",6888), ("Dell Notebook",3200), ("Bike",680), ("Mouse",365), ("earphone",1088), ("sunglass",900), ("Paython book",218), ] product_cart = [] #客户空的购物车 salary = input("please input your salary:") #客户输入自己的薪水 if salary.isdigit(): salary = int(salary) #转换为数字类型 while True: #金够的话,无限可以买 for product_code, i in enumerate(product_list,1):#enumerate遍历一个列表,同时把索引值与列表元素以对应关系, print(product_code,i) #列出产品,同时显示商品编码 customer_choice = input("please input your love product:(Q is quit)")#用户选产品 if customer_choice.isdigit(): customer_choice = int(customer_choice) #判断是否输入数字 if customer_choice <= len(product_list) and customer_choice > 0: product_choice = product_list[customer_choice-1] #判断是否输入正确的商品编码 if salary >= product_choice[1]: print("you get it") #判断钱能否支付 product_cart.append(product_choice) #可以,加购物车 salary -= product_choice[1] #同时得到余额 else: print("it isn't enough money to shopping,only %s usd" % salary)#不可以支付,加购物车 for product_number, i in enumerate(product_cart): print(product_number, i) #列出选购的商品 break #退出 else: print("there is not such product!!,please try again") #商品编码不对 elif customer_choice == "q": #客户按Q退出 print("---your shopping cart---") for product_number, i in enumerate(product_cart): print(product_number, i) #列出选购的商品 exit() else: print("please choose the right product code") #不是数字 else: print("please write right salary") #salary 错误