六、購物車程序

product_list=[
    ('Mac',9000),
    ('kindle',800),
    ('tesla',900000),
    ('python book',105),
    ('bike',2000),

]
saving=input('please input your money:')
shopping_car=[]
if saving.isdigit():
    saving=int(saving)
    while True:
        #打印商品內容
        for i,v in enumerate(product_list,1):
            print(i,'>>>>',v)

         #引導用戶選擇商品
        choice=input('選擇購買商品編號[退出:q]:')

        #驗證輸入是否合法
        if choice.isdigit():
            choice=int(choice)
            if choice>0 and choice<=len(product_list):
                #將用戶選擇商品經過choice取出來
                p_item=product_list[choice-1]

                #若是錢夠,用本金saving減去該商品價格,並將該商品加入購物車
                if p_item[1]<saving:
                    saving-=p_item[1]

                    shopping_car.append(p_item)

                else:
                    print('餘額不足,還剩%s'%saving)
                print(p_item)
            else:
                print('編碼不存在')
        elif choice=='q':
            print('------------您已經購買以下商品----------------')
            #循環遍歷購物車裏的商品,購物車存放的是已買商品
            for i in shopping_car:
                print(i)
            print('您還剩%s元錢'%saving)
            break
        else:
            print('invalid input')
相關文章
相關標籤/搜索