shoppping list

老男孩教育案例,拿出来和大家分享一下

#!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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值