python基礎之購物車

'''需求:啓動程序,讓用戶輸入工資,打印商品列表讓用戶根據商品編號購買商品選擇商品後,判斷是否足額,不足提醒,足扣款能夠隨時退出,退出顯示餘額和已購商品'''#商品列表prodnct_list = [    ('Iphonr' ,6000),    ('HUAWEI',4000),    ('Mac pro',9800),    ('Watch',12800)]#定義一個空的已買商品列表shopping_list = []salary = input('請輸入你的工資:')#判斷是否爲整數if salary.isdigit():     #isdigit:整數(不區分是不是字符串仍是數字類型)    #轉換成int類型    salary = int(salary)    while True:        #打印出商品列表及下標選項        for index,item in enumerate(prodnct_list):     #enumerate:取下標            #print(prodnct_list.index(item),item)    #index:顯示下標            print(index,item)        user_choice = input('請選擇要買的商品:')        #判斷輸入數據是否爲整數        if user_choice.isdigit():            #轉換成int類型            user_choice = int (user_choice)            #判斷輸入的整數是否小於商品列表的長度,大於等於0            if user_choice < len(prodnct_list) and user_choice >=0:              #len:顯示列表的長度                #把選中的商品取出來                p_item = prodnct_list[user_choice]                #判斷選中的商品金額是否小於等於工資金額                if p_item[1] <= salary:                    #把該商品加入到shopping_list列表中                    shopping_list.append(p_item)      #append:增長                    #在工資中減掉該商品的錢                    salary -= p_item[1]                    print("已購買[%s],餘額爲[%s] "%(p_item,salary))                else:                    print('餘額爲[%s],不能買該商品' %(salary))            else:                print('%s商品不存在'%(user_choice))        elif user_choice == 'q':            print('-----已購買以下商品-----')            for i in shopping_list:                print(i)            print('餘額爲:',salary)            exit()        else:            print('該商品不存在,請從新輸入\nq爲退出')else:    print('請輸入整數')
相關文章
相關標籤/搜索