购物车

isdgit() 判断是否是数字

enumerate()是python的内置函数
enumerate在字典上是枚举、列举的意思
对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
enumerate多用于在for循环中得到计数

# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'Wang.KuiQiang'
__mtime__ = '2017/9/19'

用户输入金额,打印商品列表
根据编号购买商品
选择后,检测余额是否足够,
可随时退出q,退出打印购买的商品和余额


"""
product_list = [
    ('iphone', 8200),
    ('Macbook pro', 9288),
    ('ipad', 3200)
]
shopping_list = []
balance = input('how much money you left?:')
if balance.isdigit():
    balance = int(balance)
    while True:
        for index, item in enumerate(product_list):
            print(index, item)
        choice = input('choice the Id number in the product list:')
        if choice.isdigit():
            choice = int(choice)
            if choice >= 0 and choice < len(product_list):
                item = product_list[choice]
                if item[1] > balance:
                    print('you don\'t have enough money ')
                else:
                    balance = balance - item[1]
                    shopping_list.append(item)
                    print('you\'ve paied %s and left %s' % (item[1], balance))
            else:
                print('the code is inexistence ')
        elif choice == 'q':
            print("--------shopping list------")
            for p in shopping_list:
                print(p)
            print("Your current balance:", balance)
            exit()
        else:
            print("invalid option")

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容