商品购物添加程序

# Author: Sure Feng
'''
aim:
启动程序后,让用户输入工资,然后打印商品列表
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
'''

# 商品列表
product_list = [('Iphone',5800),
    ('Mac Pro',9800),
    ('Bike',800),
    ('Watch',10600),
    ('Coffee',31),
    ('Alex Python',120)
                ]
# 购物列表
shopping_list = []

# 函数:打印输入错误提示
def my_wrong():
    print("""--------invalid option----------""")

# 获取用户工资
salary = input("salary: ")

# 循环判断用户工资是否正确
while True:
    # 用户工资输入正确,为整数
    if salary.isdigit():
        salary = int(salary)
        while True:
            # 打印商品列表
            for index, itme in enumerate(product_list):
                print(index, itme)
            # 用户按序号选择商品
            user_choice = input("请选择需购买的商品>>> ")
            # 用户输入序号正确
            if user_choice.isdigit():
                user_choice = int(user_choice)
                # 判断序号范围是否正确
                if user_choice < len(product_list) and user_choice >= 0:
                    user_item = product_list[user_choice]
                    # 判断用户购买能力
                    # 买得起
                    if salary > user_item[1]:
                        # 把商品加入购物列表
                        shopping_list.append(user_item)
                        #打印工资余额
                        salary -= user_item[1]
                        print("%s已成功加入购物车,所剩余额为33[31;1m%s33[0m" % (user_item[0], salary))
                        print("=========================")
                    # 买不起
                    else:
                        print("33[41;1m余额不足,只剩[%s],请及时充值~33[0m" % salary)
                else:
                # 打印输入错误提示
                    my_wrong()
            #用户输入序号错误
            elif user_choice == "q":
                print("-----shopping list------")
                for i in shopping_list:
                    print(i)
                print("33[31;1msee you next time33[0m")
                exit()
            else:
                # 打印输入错误提示
                my_wrong()

    # 用户工资输入非整数,错误。
    else:
        # 打印输入错误提示
        print("输入有误,请选择重新输入或退出!")
        # 询问是否退出购物
        user_choice = input(" 是否退出购物(q)? >>> ")
        if user_choice == "q":
            exit()
        else:
             # 重新获取用户工资,重新开始循环
            salary = input("salary: ")
原文地址:https://www.cnblogs.com/sure-feng/p/9575189.html