题干:最后一个remember_me.py版本假设用户要么已输入其用户名,要么是首次运行该程序。我们应修改这个程序,以应对这样的情形:当前和最后一次 运行该程序的用户并非同一个人。 为此,在greet_user() 中打印欢迎用户回来的消息前,先询问他用户名是否是对的。如果不对,就调用get_new_username() 让用户输入正确的用户名。
import json
def get_stored_name():
file_name='username.json'
try:
with open (file_name) as file3:
user_name=json.load(file3)
except FileNotFoundError:
get_new_username()
else:
return user_name
def get_new_username():
user_name=input('Please enter your name !')
file_name='user_name.json'
with open (file_name,'w') as file4:
json.dump(user_name,file4)
return user_name
def greet_user():
user_name=get_stored_name()
with open ('user_name.json') as file5:
user_name1=json.load(file5)
answer=input('Is this name right ?'+' Y/N: ')
if answer=='Y':
print('Welcome back !'+user_name1)
else:
user_name=get_new_username()
print("We will rememble you ,"+user_name.title()+' !')
greet_user()