day02--列表与购物车

昨晚听了一晚老师讲解的列表之后,自己也有一定的思路,购物车大概能写出来,但是还是有很多的错误,坑太多了,给自己提个醒。

我的购物车.py

sla=int(input("请输入您的工资:"))
print('''
1、A......5800
2、B......12000
3、C......31
4、D......81
5、E......800
''')
name=[["A",5800],["B",12000],["C",31],["D",81],["E",800]]
my=[]
li=[]
while True:
    k=input("你还想要继续购买吗?选择商品编号或者按“q”退出")
    if k=="q":
        break
    else:
        my.append(name[int(k)-1][0])
        li.append(name[int(k)-1][1])
        s=sum(li)
        if s>sla:
            print("您的余额不足,请选择一个删掉 :")
            print(my)
            d=input("请输入上商品编号选择商品,或者按“q”退出")
            if d=="q":
                break
            del my[int(d)-1]
            del li[int(d)-1]
            
s=sum(li)
print("你选择的商品是 ")
print(my)
print("您的余额是: "+str(sla-s))

效果能实现,中间很多地方选择错误的时候,直接就报错,而且没有考虑到:

1:如果用户输入的工资是字母之类的字符串,怎么办?

2、购买商品的时候用户输入的是字母之类的字符串呢?

3、购买商品的时候用户输入的编号大于商品的种类呢?

下面是老师的代码:

老师的购物车.py

product_list=[
    ("iphone",5000),
    ("mac pro",9800),
    ("bike",800),
    ("watch",10600),
    ("coffer",31),
    ("cup",120)
]        #用元组提示里面的内容不能更改

shopping_list=[]
salary=input("input you salary:")

if salary.isdigit():        #字符串的isidgit()方法可以用来判断输入的是否是整数,是的话,条件为true
    
    salary=int(salary)       #转换成整型
    while True:
        for k,i in enumerate(product_list):
                                               #priint(product_list.index(i),i),如果for里用一个参数的话,考虑用这种方法,index()可以获取查询的元素的位置
            print(k,i)
        user_choice=input("输入你要的商品:")
        if user_choice.isdigit():       #再次判断用户输入的是不是整数
            
            user_choice=int(user_choice)
            if user_choice<len(product_list) and user_choice>=0:       #判断用户输入的整数是不是在列表长度之内,len()方法来获取长度
                
                p_item=product_list[user_choice]       #在范围内的话,把选择的元素(也就是那个元组)取出来
                
                if p_item[1]<=salary:       #工资与商品价格比较大小
                    
                    shopping_list.append(p_item)       #购物车加入该商品
                    
                    salary-=p_item[1]       #工资减去该商品的价格
                    
                    print("加入 %s into shopping,and you current is %s"%(p_item,salary))
                else:
                    print("你的余额只剩下%s,还买个屁"%salary)
            else:
                print("商品不存在")
        elif user_choice=="q":
            print("-------shopping list------")
            for p in shopping_list:
                print(p)
            print("your current balance is %s"%salary)
            exit()

        else:
            print("您输入有误")

'''
enumerate的用法:
a=[1,2,3]
for i in enumerate(a):
print(i)
>>>
(0,1)
(1,2)
(2,3)
'''

猜你喜欢

转载自www.cnblogs.com/hhl741/p/11013239.html
今日推荐