程序練習(1)
阿新 • • 發佈:2018-03-08
目前 item 文件 菜單 {} with open art -s it!
一.商品買賣程序:
要求:1.啟動程序後,讓用戶輸入工資,然後打印商品列表;
2.允許用戶根據商品編碼購買商品
3.用戶購買商品後,檢測余額是否夠,夠就直接扣款,不夠就提醒
4.可隨時退出,退出時,打印已購買商品和余額
初始版本:
1 goods= [[‘apple‘, 6], [‘banana‘, 3], [‘orange‘, 4]] 2 shopping_cart = [] 3 4 salary = int(input("Salary:")) 5 while True: 6 for good in goods: 7 printView Code(goods.index(good)+1,". ", end="") 8 for value in good: 9 print(value,‘ ‘, end="") 10 print() 11 i = int(input(‘Which one do you want to buy?‘)) 12 if goods[i-1][1] > salary: 13 print("You don‘t have enough money!") 14 break 15 else: 16 salary = salary - goods[i-1][1]17 shopping_cart.append(goods[i-1]) 18 print(‘You balance: ‘,salary) 19 print(‘You shopping cart has: ‘,shopping_cart)
以下是優化版本:
1 goods= [[‘apple‘, 6], [‘banana‘, 3], [‘orange‘, 4]] 2 shopping_cart = [] 3 4 salary = input("Salary:") 5 if salary.isdigit(): 6View Codesalary = int(salary) 7 while True: 8 for index, good in enumerate(goods): 9 print(index+1, ‘. ‘, good) 10 user_choice = input(‘Which one do you want to buy?‘) 11 if user_choice.isdigit(): 12 user_choice = int(user_choice) - 1 13 if user_choice < len(goods) and user_choice >= 0: 14 p_items = goods[user_choice] 15 if p_items[1] <= salary: 16 shopping_cart.append(p_items) 17 salary -= p_items[1] 18 print("Add %s into shopping cart, your current balance is \033[31;1m%s\033[0m"%(p_items, salary)) 19 else: 20 print("\033[41;1mYou banlance only left [%s].\033[0m"%(salary)) 21 else: 22 print("Invalid option!") 23 elif user_choice == ‘q‘: 24 for i in shopping_cart: 25 print(i) 26 print("\033[31;1mYou banlance only left [%s].\033[0m"%(salary)) 27 exit() 28 else: 29 print("Invalid option!")
優化的地方有:
a. 5,11行增加了對輸入字符是否是純數字進行判斷,在判斷為是純數字後,將其強制轉為int類型;
若是字母q,則打印購買的物品以及剩余的工資並退出,同時其余輸入均判為非法字符;
b. 使用enumerate()得到每個元素的具體位置;
c. 13行判斷輸入的字符是否在給定範圍內;
d. 在18,20行使用 \033[31;1m()\033[0m 將()中的內容顯示高亮;
e. 這裏使用exit(0退出程序
以下是進一步優化版本:
優化的內容:
用戶入口:1.商品信息被存在文件內; 2.已購商品,余額記錄;
商家入口:1.可添加商品,修改商品的價格。
1 import time 2 3 seller = [‘seller‘, 123456] 4 buyer = [‘buyer‘, 112233] 5 6 current = input("seller or buyer?") 7 if current == "seller": 8 username = input(‘Username: ‘) 9 password = input(‘Password: ‘) 10 if password.isdigit(): 11 password = int(password) 12 if username == seller[0] and password == seller[1]: 13 print("log in......") 14 time.sleep(5) 15 with open("f_goods", "r") as f1: 16 goods = eval(f1.read()) 17 for index, good in enumerate(goods): 18 print(index + 1, ‘. ‘, good) 19 while True: 20 choice = input("change or add?") 21 if choice == "change": 22 seller_choice = input("Which one do you want to change?") 23 if seller_choice.isdigit(): 24 seller_choice = int(seller_choice) - 1 25 if seller_choice < len(goods) and seller_choice >= 0: # 判斷商家的選擇是否在目前所有商品的範圍內 26 choice = input("name or price?") 27 if choice == ‘goods‘: # 修改貨物的名稱 28 g_item = input("Good name:") 29 goods[seller_choice][0] = g_item 30 elif choice == ‘price‘: # 修改貨物的價格 31 p_item = input("Good price:") 32 if p_item.isdigit(): 33 goods[seller_choice][1] = int(p_item) 34 elif choice == ‘q‘: 35 exit() 36 else: 37 print("\033[46;1mInvalid option!\033[0m") 38 with open("f_goods", "w") as f2: #在文件中又以可讀的方式打開了f_goods 39 f2.write(str(goods)) 40 elif choice == "add": 41 good_name = input("Goods name:") 42 good_price = input("Goods price:") 43 if good_price.isdigit(): 44 list = [good_name, int(good_price)] 45 goods.append(list) 46 with open("f_goods", "w") as f2: 47 f2.write(str(goods)) 48 elif choice == ‘q‘: 49 exit() 50 else: 51 print("\033[41;1mWrong username or password!\033[0m") 52 else: 53 print("\033[38;1mInvalid option!\033[0m") 54 55 56 elif current == "buyer": 57 username = input(‘Username: ‘) 58 password = input(‘Password: ‘) 59 if password.isdigit(): 60 password = int(password) 61 if username == buyer[0] and password == buyer[1]: 62 print("log in......") 63 time.sleep(5) 64 with open("f_goods", "r") as f1, open("f_cart", "r") as f2: 65 goods = eval(f1.read()) 66 cart_info = eval(f2.read()) 67 for index, good in enumerate(goods): 68 print(index + 1, ‘. ‘, good) 69 banlance = cart_info["banlance"] 70 shopping_cart = cart_info["shopping_cart"] 71 print("Banlance:", banlance) 72 while True: 73 user_choice = input(‘Which one do you want to buy?‘) 74 if user_choice.isdigit(): 75 user_choice = int(user_choice) - 1 76 if user_choice < len(goods) and user_choice >= 0: 77 p_items = goods[user_choice] 78 if p_items[1] <= banlance: 79 shopping_cart.append(p_items) 80 banlance -= p_items[1] 81 print("Add %s into shopping cart, your current balance is \033[31;1m%s\033[0m" % ( 82 p_items, banlance)) 83 else: 84 print("\033[41;1mYou banlance only left [%s].\033[0m" % (banlance)) 85 else: 86 print("Invalid option!") 87 elif user_choice == ‘q‘: 88 for i in shopping_cart: 89 print(i) 90 print("\033[31;1mYou banlance only left [%s].\033[0m" % (banlance)) 91 cart_info["banlance"] = banlance 92 cart_info["shopping_cart"] = shopping_cart 93 with open("f_cart", "w") as f3: 94 f3.write(str(cart_info)) 95 exit() 96 else: 97 print("Invalid option!") 98 99 else: 100 print("Invalid option!") 101 102 #用到的文件 103 f_goods = [[‘banana‘, 3], [‘orange‘, 4], [‘apple‘, 5], [‘sweets‘, 20]] 104 f_cart = {‘shopping_cart‘: [], ‘banlance‘: 100} #初始余額為100元View Code
這裏還可以進一步優化,比如進行代碼的重構,增添用戶入口的清空購物車以及充值功能,以及商家入口的刪除商品功能等。
二.多級菜單程序
1 solar_system = {‘_earth‘: {‘_sky‘: {‘bird‘: ‘fly‘}, 2 ‘_ocean‘: {}, 3 ‘_mountain‘: {} 4 }, 5 ‘_moon‘: None, 6 ‘_mars‘:{‘mars‘: {}} 7 } 8 9 exit_flag = True 10 while exit_flag: 11 for key1 in solar_system.keys(): 12 print(key1) 13 choice1 = input("Which one would you want to watch?") 14 if choice1 in solar_system.keys(): 15 if solar_system[choice1]: 16 for key2 in solar_system[choice1].keys(): 17 print(key2) 18 choice2 = input("Which one would you want to watch?") 19 if choice2 in solar_system[choice1].keys(): 20 if solar_system[choice1][choice2]: 21 for key3 in solar_system[choice1][choice2].keys(): 22 print(key3) 23 choice3 = input("Would you want you exit?") 24 if choice3 == ‘q‘: 25 exit_flag = False 26 else: 27 print("\033[41;1mInvalid input!\033[0m") 28 else: 29 print("\033[41;1mNot exit!\033[0m") 30 elif choice1 == ‘q‘: 31 exit_flag = False 32 else: 33 print("\033[41;1mInvalid input!\033[0m") 34 else: 35 print("\033[41;1mNot exit!\033[0m") 36 elif choice1 == ‘q‘: 37 exit_flag = False 38 else: 39 print("\033[41;1mInvalid input!\033[0m")View Code
一層一層好復雜,並且還有好多弊端,比如,各下層的技術不同,無法處理字符串等。
程序練習(1)