标签:user try print macbook 写入内容 购物车 except 覆盖 otf
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
标签:user try print macbook 写入内容 购物车 except 覆盖 otf
原文地址:https://www.cnblogs.com/hiuhungwan/p/9278837.html