import json
def get_stored_username():
"""Get stored username if available."""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""Prompt for a 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():
"""Greet the user by name."""
username = get_stored_username()
if username:
correct = input("Are you " + username + "? (y/n) ")
if correct == 'y':
print("Welcome back, " + username + "!")
return
# We got a username, but it's not correct.
# Let's prompt for a new username.
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
greet_user()
上面代码中的函数greet_user()
应该根据以下文本重写:
唯一要解决的是嵌套的if
语句。可以通过将用于检查用户名是否正确的代码移到单独的函数来清除此问题。如果您喜欢这个练习,可以尝试创建一个名为check_username()
的新函数,看看是否可以从if
中删除嵌套的greet_user()
语句。
这是我尝试解决此问题的尝试:
def greet_user():
"""Greet the user by name."""
username = get_stored_username()
if username:
check_username()
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
def check_username():
correct = input("Are you " + username + "? (y/n) ")
if correct == 'y':
print("Welcome back, " + username + "!")
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
这是IDLE的输出:
Traceback (most recent call last):
File "C:\Users\Documents\python_work\files and exceptions\JSON\remember_me.py", line 41, in <module>
greet_user()
File "C:\Users\Documents\python_work\files and exceptions\JSON\remember_me.py", line 29, in greet_user
check_username()
File "C:\Users\Documents\python_work\files and exceptions\JSON\remember_me.py", line 34, in check_username
correct = input("Are you " + username + "? (y/n) ")
UnboundLocalError: local variable 'username' referenced before assignment
该程序的工作方式如下:
What is your name? eric
We'll remember you when you come back, eric!
Are you eric? (y/n) y
Welcome back, eric!
Are you eric? (y/n) n
What is your name? ever
We'll remember you when you come back, ever!
Are you ever? (y/n) y
Welcome back, ever!
答案 0 :(得分:2)
在该范围内,您没有变量username
。您在great_user
中有一个具有该名称的局部变量,但尚未将其传递给check_username
。只需添加该参数/参数。
def greet_user():
"""Greet the user by name."""
username = get_stored_username()
if username:
check_username(username)
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
def check_username(username):
correct = input("Are you " + username + "? (y/n) ")
if correct == 'y':
print("Welcome back, " + username + "!")
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
此外,您的流量控制不舒服。 check_username
只能这样做,返回其状态,并让新用户的注册保留为此目的已经编写的功能。