购物车案例

这个是我写的代码思路,首先是定义商品列表结构,这里我一开始的思路是放了商品编号,商品名还有商品价钱,然后再定义个列表,存放用户的订购的商品,这样子就不够有灵性了。下面再说为什么不够灵性。

接着是输入汇入金额,在这里我没有做判断输入的金额是否是数字,是失败之一,主要是我不知道怎么转,后来听老师讲,知道了这个方法(输入的字符).isdigit()判断是否为数字,当然,我没有用上这个。然后就是进入死循环,遍历商品列表,展示有什么商品给用户。接着让用户输入,如果用户输入了exit,则退出程序,打印已经订购的商品,如果不是,则进行强转,这里也是缺陷之一,因为虽然用户输出的不是exit,但是有可能输入其它的字符串,从而导致程序崩溃,这是失败之一。不过7,8分钟,不查什么东西,我觉得自己初步的思路,也还ok。如果用户订购的商品编号在列表里面,则加入列表,如果不是,则提示用户输入的商品编号不存在。

# -*- coding:utf-8 -*-
# author:ke_T
commodity = [[1,"iphone8",6000], [2,"iphonex",10000], [3,"三星s8",6000],
[4, "小米笔记本pro", 5000], [5, "huaweip10", 6500], [6, "诺基亚3052", 4000]]
shop_car =[]
money = int(input("请输入你汇入的金额"))
buy = 0
while True:
print("商品编号","商品","价格")
for i in commodity:
print(i[0],"\t",i[1],i[2])
number = input("请输入你要购买的商品的编号,如果要退出,请输入exit\n")
if(number == "exit"):
break
else:
shop_index = int(number)
if(shop_index<len(commodity) and shop_index > 0):
if ((money - buy) > commodity[shop_index - 1][2]):
shop_car.append(commodity[shop_index - 1])
buy += commodity[shop_index - 1][2]
else:
print("您的余额不足以购买", commodity[shop_index - 1][1])
continue
else:
print("请检查你的输入的商品编号是否正确,找不到该商品编号",shop_index)
continue

print("您的购物车商品编号", "商品", "价格")
for i in shop_car:
print(i[0], "\t", i[1], i[2])
print("余额还剩下",money-buy,"共花费了",buy,"元")
总的来说,我的思路并不怎么好,有两个缺陷,一个是商品编号写死了,一个是用户输入的东西,没有进行是否符合规定的判断。
下面展示一个好的做法的代码:

product_list = [
('Iphone',5800),
('Mac Pro',9800),
('Bike',800),
('Watch',10600),
('Coffee',31),
('Alex Python',120),
]
shopping_list = []
salary = input("Input your salary:")
if salary.isdigit(): #判断是否是数字
salary = int(salary)
while True:
for index,item in enumerate(product_list): #index表示下标,item指向列表的值
#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(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")

这个代码就考虑得不错,不限定商品编号的坐标,并且判断用户输入是否非法从而执行相应的操作。这里面涉及了3个我不知道的东西。一个是
for index,item in enumerate(product_list):    #index表示下标,item指向列表的值
一个是字符串的.isdigit()方法,判断是否为数字,还有\033[31;1m%s\033[0m,会加粗相应的内容。

当然了,这些没有涉及到数据库,许多东西就不是很实际啦。不过最重要的是思路的锻炼吧,让逻辑更加严谨。



posted on 2017-09-24 20:09  柯腾  阅读(206)  评论(0编辑  收藏  举报