python购物车程序

  第一次发文章,记录自己学习的记录,只是我初学python所自己写的程序,往后会慢慢累计随笔。

  这是一个基于python写的购物车程序。

  这个购物车运用了python的知识点为:

列表,用户输入,for循环,while循环,列表坐标,if判断。

程序流程:首先我们要让用户输入自己的金额,输入玩金额后,物品会自动呈现给用户,让用户选择,或者按q结束购买,当用户选择的同时购物车会自动保存用户所选择的物品,并会把用户一开始输入的总金额减去该物品的价格。

以下是代码。

product_list = [
('Mac',9000),
('kindle',800),
('tesla',900000),
('python book',105),
('bike',2000),
]
shopping_car = [] #这个到后面才定义的,用于把选的物品放进这个变量里面。
saving = input("please input your saving:")
if saving.isdigit():
saving = int(saving)
while True:

#打印商品内容
for i,x in enumerate(product_list,1): # enumerate函数,一般用在 for 循环当中
print(i,x)

#引导用户选择商品
choice = input('选择购买商品编号:[退出:q]')
#验证输入是否合法
if choice.isdigit():
choice = int(choice)
if choice > 0 and choice <= len(product_list): #这里len(product_list)主要是为了以后加商品不用每次都来改这个参数,就会变得灵活
#将用户选择商品取出来
p_item = product_list[choice-1]
#如果钱够,用本金saving减去该商品价格,并将商品加入购物车
if p_item[1] < saving:
saving-=p_item[1]
shopping_car.append(p_item)


else:
print("余额不足,还剩下%s"%saving)
print(p_item)
else:
print('编码不存在')


elif choice == "q":
print("--------您已经购买以下商品----------")
#循环遍历购物车里的商品,购物车存放的是已买的商品。
for i in shopping_car:
print(i)
print("您还剩%s元钱"%saving)
break;
else:
print("invalid input")


最后,十分感谢老男孩的alex老师和小月月老师,本人是通过视频学习的,因为还是个苦逼的打工仔,等实现自己想做的工作后,一定请各位大佬吃饭。


 

posted on 2019-06-10 20:03  身侧白手  阅读(155)  评论(0编辑  收藏  举报