python3 購物車小程序,余額寫入文件保存
阿新 • • 發佈:2018-07-08
brush pac usr .exe edm fin 關閉 process lis
python3 購物車小程序,余額寫入文件保存
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Hiuhung Wan goods = ( ("MiNote3", 2499), ("Bike", 799), ("MacBook", 6999), ("Coffee", 25), ("RedMiNote3", 1099), ("Python 3", 59) ) def main(): ‘‘‘ 入口 :return: ‘‘‘ # 創建一個文件,用於存儲余額。 try: with open(‘balance.txt‘, ‘r‘) as f: data_str = f.read() if data_str and (not data_str.isspace()): # 有內容, balance = int(data_str) else: # 有文件,但沒有內容 balance = input("請輸入您的錢包余額:") if balance.isnumeric(): balance = int(balance) else: print("請輸入正整數") exit() with open(‘balance.txt‘, ‘w‘) as f: f.write(str(balance)) except FileNotFoundError as e: # 沒有這個文件,就創建並寫入內容 balance = input("請輸入您的錢包余額:") if balance.isnumeric(): balance = int(balance) else: print("請輸入正整數") exit() with open(‘balance.txt‘, ‘w‘) as f: f.write(str(balance)) finally: f.close() # 關閉文件。 go_back_flag = True shopping_list = [] while go_back_flag: for i, j in enumerate(goods): print(i, j) user_chiose = input("錢包余額是:% .2f,您要買什麽?" % (balance)) if user_chiose == ("q" or "Q"): go_back_flag = False continue elif user_chiose.isnumeric(): user_chiose = int(user_chiose) else: print("請輸入上面的序號") continue if user_chiose <= len(goods) - 1: #符合 if goods[user_chiose][1] <= balance: #買得起 balance -= goods[user_chiose][1] with open(‘balance.txt‘, ‘w‘) as f: # 更新余額(覆蓋) f.write(str(balance)) f.close() print("已將 %s 加入您的購物車" %(goods[user_chiose][0])) shopping_list.append(goods[user_chiose]) else: print("余額不足,買不了。") else: print("超出範圍,沒有這個序號") print("您的錢包余額是:%.2f。" %(balance)) if len(shopping_list) == 0: print("您都沒有買東西") else: print("下面將列出你已購買的商品") for i in shopping_list: print(i) if __name__ == "__main__": main()
效果如下:
C:\Python36\python.exe D:/Py/1704/day05/購物車.py 請輸入您的錢包余額:6666 0 (‘MiNote3‘, 2499) 1 (‘Bike‘, 799) 2 (‘MacBook‘, 6999) 3 (‘Coffee‘, 25) 4 (‘RedMiNote3‘, 1099) 5 (‘Python 3‘, 59) 錢包余額是: 6666.00,您要買什麽?3 已將 Coffee 加入您的購物車 0 (‘MiNote3‘, 2499) 1 (‘Bike‘, 799) 2 (‘MacBook‘, 6999) 3 (‘Coffee‘, 25) 4 (‘RedMiNote3‘, 1099) 5 (‘Python 3‘, 59) 錢包余額是: 6641.00,您要買什麽?2 余額不足,買不了。 0 (‘MiNote3‘, 2499) 1 (‘Bike‘, 799) 2 (‘MacBook‘, 6999) 3 (‘Coffee‘, 25) 4 (‘RedMiNote3‘, 1099) 5 (‘Python 3‘, 59) 錢包余額是: 6641.00,您要買什麽?1 已將 Bike 加入您的購物車 0 (‘MiNote3‘, 2499) 1 (‘Bike‘, 799) 2 (‘MacBook‘, 6999) 3 (‘Coffee‘, 25) 4 (‘RedMiNote3‘, 1099) 5 (‘Python 3‘, 59) 錢包余額是: 5842.00,您要買什麽?q 您的錢包余額是:5842.00。 下面將列出你已購買的商品 (‘Coffee‘, 25) (‘Bike‘, 799) Process finished with exit code 0
python3 購物車小程序,余額寫入文件保存