列表元组练习一例

Posted richard-liang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了列表元组练习一例相关的知识,希望对你有一定的参考价值。

知识点:

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 33[32;1m%s33[0m%(product_list[select_num],salary))
            else:
                # 高亮显示,41为底色红色高亮42为绿色
                print(33[41;1mYour acount balance is not enough33[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)

 

以上是关于列表元组练习一例的主要内容,如果未能解决你的问题,请参考以下文章

python元组,列表,字典练习

组合数据类型练习,英文词频统计实例上列表,元组,字典,集合的遍历。 总结列表,元组,字典,集合的联系与区别。

列表,元组,字典,集合 练习题

组合数据类型综合练习

元组 字体高亮 购物车练习

列表元组字典集合的相关练习