宁静消失何如

导航

 

程序练习 

请闭眼写出以下程序。

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额   
__author__ = 'LEE'
# -*- coding: utf-8 -*-
# 商品列表不可以做死
product_list = [('Iphone', 5800), # ('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) # 如果是数字 改变数据类型为 int
while True:
# for item in product_list:
# print(product_list.index(item)+1, item) # 可以打印出序号
for index,item in enumerate(product_list): # 列出序号 enumerate吧把下标取出来
print(index,item)
user_choice = input("选择要买嘛?>>>:") # 让用户选择买什么东西
if user_choice.isdigit(): # 判断用户输入数据必须是数字类型
user_choice = int(user_choice) # 如果是数字 改变数据类型为 int
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) # 添加在商品list里
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("[%s]商品不存在!" % user_choice)
elif user_choice == 'q':
print('exit...')
print("--------------shopping list------------")
for p in shopping_list:
print(p)
print("your current balance:",salary)
exit()
else:
print("invalid option")
posted on 2017-03-10 09:41  宁静消失何如  阅读(134)  评论(0)    收藏  举报