老男孩教育案例,拿出来和大家分享一下
#!coding:utf-8
# Author:pymingming
product_list = [
('Iphone', 5800),
('Mac Pro', 9800),
('Bike', 820),
('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
#print(product_list.index(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('your salary can not afford this good,please choose others')
else:
print('your choose not exist,please choose again ')
elif user_choice == 'q':#如果输入q,则打印退出
items = []
for item in shopping_list:
items.append(item)
print('you have already choose\033[32;1m [%s]\033[0m in your shopping list!'%items)
print('you have \033[31;1m%s\033[0m salary left'%salary)
exit()
else:
print('invalid option')
else:
print('invalid option')
PS J:\pymingming\day3> python shopping.py
Input your salary:5000
0 ('Iphone', 5800)
1 ('Mac Pro', 9800)
2 ('Bike', 820)
3 ('watch', 10600)
4 ('Coffee', 31)
5 ('Alex python', 120)
选择商品代号:4
Added ('Coffee', 31) into shopping cart,your current balance is 4969
0 ('Iphone', 5800)
1 ('Mac Pro', 9800)
2 ('Bike', 820)
3 ('watch', 10600)
4 ('Coffee', 31)
5 ('Alex python', 120)
选择商品代号:5
Added ('Alex python', 120) into shopping cart,your current balance is 4849
0 ('Iphone', 5800)
1 ('Mac Pro', 9800)
2 ('Bike', 820)
3 ('watch', 10600)
4 ('Coffee', 31)
5 ('Alex python', 120)
选择商品代号:0
your salary can not afford this good,please choose others
0 ('Iphone', 5800)
1 ('Mac Pro', 9800)
2 ('Bike', 820)
3 ('watch', 10600)
4 ('Coffee', 31)
5 ('Alex python', 120)
选择商品代号:q
you have already choose [[('Coffee', 31), ('Alex python', 120)]] in your shopping list!
you have 4849 salary left