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()
The function greet_user()
in the code above should be rewritten according to the text below:
The only thing left to address is the nested if
statements. This can be cleaned up by moving the code that checks whether the username is correct to a separate function. If you’re enjoying this exercise, you might try making a new function called check_username()
and see if you can remove the nested if
statement from greet_user()
.
This is my attempt in try to solve this problem:
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 + "!")
This is the output from the 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
This is how the program is supposed to work like:
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!