Python實踐:購物車
阿新 • • 發佈:2018-12-10
購物車程式
- 要求如下圖
- 程式碼
# --*--coding:utf-8--*-- # Author: 村雨 import pprint productList = [('Iphone 8', 10000), ('GTX2080', 8000), ('Z7KP7-GT', 6000), ('Mac pro', 15000), ('Honor 10', 2800), ('Iphone XR', 12000), ('Mi 8', 2999) ] shoppingList = [] print('輸入你的工資:') salary = input() if not salary.isdigit(): print('請輸入整數') else: salary = int(salary) while True: for index, item in enumerate(productList): print(index + 1, item) print('輸入你要買的商品的序號:') userWant = input() if userWant.isdigit(): userWant = int(userWant) if userWant <= len(productList) and userWant > 0: print('你要購買的是:', productList[userWant - 1][0]) if salary >= productList[userWant - 1][1]: shoppingList.append(productList[userWant - 1][0]) salary -= productList[userWant - 1][1] print('你已經購買了' + productList[userWant - 1][0] + ', 你的餘額為 ' + str(salary)) else: print('對不起,你的餘額不足!請努力工作吧!') print('你當前所購買的商品為:') for brought in shoppingList: pprint.pprint(brought) print('你當前餘額為:', salary) exit() else: print('你輸入的商品序號有錯,請重新輸入') elif userWant == 'q': print('-----------Shopping List----------') for brought in shoppingList: pprint.pprint(brought) print('你的餘額為 ', salary) exit() else: print('Invalid input!!!')
- 結果