练习 10-11 喜欢的数
编写一个程序,提示用户输入喜欢的数,并使用 json.dump() 将这个数存储到文件中。再编写一个程序,从文件中读取这个值,并打印如下所示的消息。
I know your favorite number!It's _________.
1 import json 2 3 filename = 'number.json' 4 5 with open(filename, 'w') as f: 6 number = input("Please enter your favorite number: ") 7 number = int(number) 8 json.dump(number, f)
1 import json 2 3 filename = 'number.json' 4 5 with open(filename) as f: 6 number = json.load(f) 7 print(f"I know your favorite number! It's {number}")
练习 10-12 记住喜欢的数
将练习10-11中的程序合二为一。如果存储了用户喜欢的数,就像用户显示它,否则提示用户输入喜欢的数并将其存储到文件中。运行这个程序两次,看看它能否像预期的那样工作。
1 import json 2 3 filename = 'favorite_number.json' 4 5 try: 6 with open(filename) as f: 7 number = json.load(f) 8 except FileNotFoundError: 9 with open(filename, 'w') as f: 10 number = input("Please enter your favorite number: ") 11 number = int(number) 12 json.dump(number, f) 13 print("We will remeber your favorite number.") 14 else: 15 print(f"I know your favorite number. It's {number}")