练习10-13 验证用户
最后一个remember_me.py 版本假设用户要么已输入用户名,要么是首次运行该程序。我们应该修改这个程序,以防当前用户并非上次运行该程序的用户。
为此,在 greet_user() 中打印欢迎用户回来的消息前,询问他用户名是否正确。如果不对,就调用 get_new_username() 让用户输入正确的用户名。
1 import json
2
3 def get_stored_username():
4 '''如果存储了用户名,就获取它'''
5 filename = 'username.json'
6 try:
7 with open(filename) as f:
8 username = json.load(f)
9 except FileNotFoundError:
10 return None
11 else:
12 return username
13
14 def get_new_username():
15 '''提示用户输入用户名'''
16 username = input("Please enter your username: ")
17 filename = 'username.json'
18 with open(filename, 'w') as f:
19 json.dump(username, f)
20 return username
21
22 def greet_user():
23 """基于用户名问候用户"""
24 username = get_stored_username()
25 if username:
26 correct = input(f"Are you {username}? (y/n)")
27 if correct == 'y':
28 print(f"Welcome back, {username}!")
29 else:
30 username = get_new_username()
31 print(f"We'll remember you when you come back, {username}!")
32 else:
33 username = get_new_username()
34 print(f"We'll remember you when you come back, {username}!")
35
36 greet_user()