一、流程為,輸入你有多少錢,然后回圈購買商品,輸入‘q’ 退出程式
1 goods=[['蘋果',6500],['華為',4999],['小米',2999],['oppo',3599]] #初始化串列,填入資料 2 mgoods=[] 3 exit_flag = False #設定一個開關 4 money=input("輸入你的錢:") 5 if money.isdigit(): #判斷是否為數字 6 while not exit_flag: 7 for index, item in enumerate(goods): #回圈遍歷串列內容,enumerate方法是把串列組成一個索引序列,同時列出資料和資料下標 8 print(index, item) #index 為索引下標 9 numbres = input("輸入購買商品的序號:") 10 #if numbres !='q' and numbres !='Q': 11 if numbres.isdigit(): 12 numbres = int(numbres) #把一個字符轉換成數字 13 if numbres< len(goods) and numbres >=0: #判斷輸入的序號(索引下標),是否有該對應的商品 14 money = int(money) 15 numbres_goods=goods[numbres][1] #串列切片,只取商品價格的欄位 16 if money >= numbres_goods: 17 money=money-numbres_goods 18 mgoods.append(goods[numbres]) #把用戶買過的商品存放在一個新的串列里 19 print('購買商品成功:'+goods[numbres][0]) 20 print('剩余金錢:\033[31;1m %s \33[0m' % money ) 21 else: 22 print('余額不足!') 23 elif numbres=='q' or numbres=='Q': 24 print('你購買的商品如下:') 25 for i in mgoods: 26 print(i) 27 break 28 else: 29 print('輸入錯誤!!') 30 else: 31 print('輸入錯誤!!,重新輸入')
學習無止境,加油
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/186840.html
標籤:Python
