1. 程式人生 > >購物車程序練習

購物車程序練習

執行 true log [] 購物 不足 one img info

購物車程序需求:

技術分享圖片

代碼如下:

#coding=utf-8

salary=input(‘請輸入工資:‘)
goods=[[‘iphone‘,5800],[‘book‘,30],[‘bike‘,800]] #商品列表
shopping_list=[] #購物車列表

if salary.isdigit(): #判斷是否數字
    salary=int(salary)
    while True:
        for index,item in enumerate(goods): #枚舉可同時獲得索引和值
            print(index,item)
        user_choice = input(‘請選擇編號:‘)
        if user_choice.isdigit():
            user_choice=int(user_choice)
            if user_choice<len(goods) and user_choice>=0:
                p_item=goods[user_choice]
                if p_item[1]<=salary: #買的起
                    shopping_list.append(p_item)
                    salary-=p_item[1]
                    print(‘商品%s已加入購物車,當前余額為\033[32;1m%s\033[0m‘%(p_item[0],salary)) #余額高亮綠色32
                else:
                    print(‘余額為\033[31;1m%s\033[0m 不足支付,請另選商品,或按q退出‘%salary)#余額高亮紅色31

        elif user_choice==‘q‘:
            print(‘-------shopping list-------‘)
            for p in shopping_list: #打印購物車列表
                print(p)
            print(‘你的當前余額為\033[31;1m%s\033[0m‘%salary)
            exit() #退出

        else:
            print(‘無效操作‘)

  

執行效果:

技術分享圖片

購物車程序練習