优化了上一个购物车程序:http://www.cnblogs.com/klvchen/p/8577269.html
#输入工资
salary = input("Please input your salary: ")
#判断工资是否为整数 if salary.isdigit(): salary = int(salary) else: exit("you must input digit")
#定义购物车 cart = [] #商品信息 msg = [["iphone6s", 5800], ["mac book", 9000], ["coffee", 32], ["bicycle", 1500]] while True:
#展示商品信息 for k, v in enumerate(msg, 1): print("%s 商品名称: %s, 价格: %d" % (k, v[0], v[1])) choice = input("Please select the product number you need to purchase ! [q] to exit")
#退出 if choice == 'q': print("========== You have buy ==========") for l in cart: print(l) exit()
#选择商品 if choice.isdigit(): choice = int(choice) if 0 < choice <= len(msg):
#判断余额是否充足 if salary >= msg[choice-1][1]: salary -= msg[choice-1][1] print("You have buy %s, money has %d" %(msg[choice-1][0], salary)) cart.append(msg[choice-1][0]) else: print("You don't you enough money! money has %d" %salary ) else: print("Please select right product number!") else: print("Please select right options")
运行结果如下:
程序还有很多可以优化的地方,以后有空再琢磨~