#10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用 #json.dump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打 #印消息“I know your favorite number! It’s _____.”。 def sorted_favourite_num(): file_1 = 'favourite_num.json' num = input('enter one you favourite number: ') with open(file_1,'w') as file_ojt: json.dump(int(num),file_ojt) def read_num(): with open('favourite_num.json') as file_obj: num = json.load(file_obj) print("I know your favorite number! It’s {}".format(num)) sorted_favourite_num() read_num()
10-12 记住喜欢的数字:将练习 10-11 中的两个程序合而为一。如果存储了用户喜 欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运 行这个程序两次,看看它是否像预期的那样工作
def sorted_favourite_num(): file_1 = 'favourite_num.json' try: with open(file_1) as file_obj: num = json.load(file_obj) except FileNotFoundError: return None else: return num def get_new_num(): num = input('enter one you favourite number: ') file_1 = 'favourite_num.json' with open(file_1,'w') as file_ojt: json.dump(int(num),file_ojt) return num def read_num(): num = sorted_favourite_num() if num: print("I know your favorite number! It’s {}".format(num)) else: num = get_new_num() print("I know your favorite number! It’s {}".format(num)) read_num()
10-13 验证用户:最后一个 remember_me.py 版本假设用户要么已输入其用户名,要么是首次运行该程序。我们应修改这个程序,以应对这样的情形:当前和最后一次运行 该程序的用户并非同一个人。 为此,在 greet_user()中打印欢迎用户回来的消息前,先询问他用户名是否是对的。 如果不对,就调用 get_new_username()让用户输入正确的用户名
import json def get_stored_username(): filename = 'username.json' try: with open(filename) as file_obj: username = json.load(file_obj) except FileNotFoundError: return None else: return username def get_new_username(): username = input("What is your name? ") filename = 'username.json' with open(filename, 'w') as f_obj: json.dump(username, f_obj) return username def greet_user(): username = get_stored_username() if username: y_n = input('Is ' + username + ' your name?(y/n)') if y_n == 'y': print("Welcome back, " + username + "!") else: username = get_new_username() print("We'll remember you when you come back, " + username + "!") else: username = get_new_username() print("We'll remember you when you come back, " + username + "!") greet_user()