列表元组练习一例

知识点:

str.isdigit() 可以判断字符串能否被转换为int类型

enumerate() 枚举list里边的内容

格式化高亮显示的方法

product_list = [
('Iphone',5800),
    ('Mac Pro',9800),
    ('Bike',800),
    ('Watch',10600),
    ('Coffee',31),
    ('Alex Python',120),
]
shopping_cart = []

salary = input('Please input your salary:')

#isdigit函数可以判断字符串能否被转换为int类型
if salary.isdigit():
    salary = int(salary)
    #使用enumerate枚举product_list里边的内容
    for index,item in enumerate(product_list):
        print(index,item)

    while True:
        select_num = input('Please select the product_num:')
        if select_num.isdigit():
            select_num = int(select_num)
            if salary >= product_list[select_num][1]:
                salary -= product_list[select_num][1]
                shopping_cart.append(product_list[select_num])
                #高亮显示,31为字体红色高亮,32为绿色
                print('%s has been put in your shopping cart. You salary remain \033[32;1m%s\033[0m'%(product_list[select_num],salary))
            else:
                # 高亮显示,41为底色红色高亮42为绿色
                print('\033[41;1mYour acount balance is not enough\033[0m,you remain balance is {0}'.format(salary))
                break
        elif select_num == 'q':
            break
        else:
            print('Your input is invalid.')
            break
print('Shopping is end, you have bought:')
for i in shopping_cart:
    print(i)

测试结果

Please input your salary:5555
0 ('Iphone', 5800)
1 ('Mac Pro', 9800)
2 ('Bike', 800)
3 ('Watch', 10600)
4 ('Coffee', 31)
5 ('Alex Python', 120)
Please select the product_num:2
('Bike', 800) has been put in your shopping cart. You salary remain 4755
Please select the product_num:3
Your acount balance is not enough,you remain balance is 4755
Shopping is end, you have bought:
('Bike', 800)

猜你喜欢

转载自www.cnblogs.com/Richard-Liang/p/10747553.html