Python代码之购物车



# -*- coding:utf-8 -*-
#Author:Mr Gan

不足之处:输入商品编号时必须是整型,其他类型会报错
import sys
balance = int(input("your money:"))
shopping_bag = [] #创建购物包
shopping_list = [["iphone",5800],["watch",2600],["book",56],["computer",7800]]

while True:
for index,i in enumerate (shopping_list):
print(index,i)
pro_num = input("production number:")

with open("余额文件",'w+') as left_money:
if pro_num == "q":
left_money.write(balance)
print("your balance left \033[31;1m%s\033[0m" % balance)
sys.exit()
elif pro_num.isdigit(): #判断输入的商品编号是否是数字
pro_num = int(pro_num)
#pro_name = shopping_list[pro_num]

if 0<= pro_num <len(shopping_list):# and pro_name[1] <= balance: # 动态判断,不要写死掉
pro_name = shopping_list[pro_num]
if pro_name[1] <= balance:
shopping_bag.append(shopping_list[pro_num][0])
balance -= pro_name[1]
else:
print("your banlance is not ennough,please choose others")
else:
print("no production,choose again")
for i in shopping_bag: #遍历已购买的商品
print("\033[31;1m%s\033[0m" % i)#打印所有已经购买的商品
print("your balance left \033[31;1m%s\033[0m" % balance)
pass
posted @ 2017-05-08 15:24  MK3945  阅读(278)  评论(0编辑  收藏  举报