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("What is your name? ")
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 print(f"Welcome back, {username}!")
27 else:
28 username = get_new_username()
29 print(f"We'll remember you when you come back, {username}!")
30
31 greet_user()