python之购物车version 2.0

本文介绍了一个简单的购物车程序实现,通过Python代码演示了如何让用户选择商品并进行结算的过程。程序首先定义了一系列商品及其价格,然后提示用户输入工资,并允许用户挑选商品,直到工资不足以支付所选商品为止。
#author:zhouyu
produce_list = [
    ('Watch'
,1000),
    ('Telephone',6500),
    ('Television',4500),
    ('refrigerate',2300),
    ('washer',680),
    ('compute',5500)
]
#
定义一个空的列表,表示购物车
shopping_list = []
#让用户输入工资
salary = input("Please input your salary: ")
#isdigit这个函数是用来判断这个salary是不是数字字符串,如果是就为True
if salary.isdigit():
#把工资转化为整数型
    salary = int(salary)
    while True:
#列出商品,enumerate这个函数可以列出这个列表的索引,按照下面方法来实验。
        for index,i in enumerate(produce_list):
           
print(index,i)
#让用户输入自己想要的商品
        user_choose = input("Please input the number of what do you want: ")
        if
user_choose.isdigit():
           
user_choose = int(user_choose)
#len函数可以列出列表的个数。
            if user_choose >= 0 and user_choose < len(produce_list):
#定义一个函数,这个函数等于用户选择的商品
                p_item = produce_list[user_choose]
#判断用户选择的商品的价格是否大于工资
                if p_item[1] <= salary:
#用户选择的商品小于工资则把商品加入到shopping_list上
                    shopping_list.append(p_item)
#用户购买这个商品后,工资就会自动减少
                    salary -= p_item[1]
                   
print("Add %s into shopping cart,and your balance is \033[31;1m%d\033[0m" %(p_item[0],salary))
#用户选择的商品大于工资则输出下面信息
                else:
                   
print("\033[41;1myour balance is not enough,get out there!!!\033[0m")
#如果用户输入的数字还是大于0小于len(produce_list)的话就输出以下信息
            else:
               
print("\033[41;1mthe produce is not exists!!!\033[0m")
#如果用户输入q就表示quit,就打印出用户购买的商品和余额并退出
        elif user_choose == 'q':
           
print("----------product list -----------")
            for
i in shopping_list:
               
print(i)
           
print("your balance is ", salary)
           
exit(1)
#如果用户输入的不是数字字符串就输出以下信息
        else:
           
print("Invali number !!!")

 


本文转自 周子琪 51CTO博客,原文链接:http://blog.51cto.com/izhouyu/1964012


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值