1. 项目
编写一个程序,提示用户输入他喜欢的数字,并使用json.dump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favorite number! It’s _____.”。
2. 代码
import json def get_favorite_number(): """如果存储了喜欢的数字,就获取它""" filename = 'favorite_number.json' try: with open(filename) as f_obj: favorite_number = json.load(f_obj) except FileNotFoundError: return None else: return favorite_number def get_new_number(): """提示用户输入喜欢的数字""" favorite_number = input("What's your favorite number? ") filename = 'favorite_number.json' with open(filename, 'w') as f_obj: json.dump(favorite_number, f_obj) return favorite_number def read_number(): """读取喜欢的数字,并打印一段话""" favorite_number = get_favorite_number() if favorite_number: print("I know your favorite number! It's " + favorite_number + " .") else: favorite_number = get_new_number() print("I know your favorite number! It's " + favorite_number + " .") read_number()
3. 执行结果
没有favorite_number.json文件就创建一个。如果有就直接打印结果。