76.6k views
5 votes
I need help with this python exercise:

Verify User:

The final listing for remember_me.py assumes either that the user has already entered their username or that the program is running for the first time. We should modify it in case the current user is not the person who last used the program.

Before printing a welcome back message in greet_user(), ask the user if this is the correct username. If it’s not, call get_new_username() to get the correct username.

Also, use a check_username() function to prevent any nested if statements from occurring in greet_user()

User Tbrk
by
8.4k points

1 Answer

5 votes

No prob. Let's go over the Python code,

Here's your complete Python program with the added function `check_username()`:

```

import json

filename = 'username.json'

def get_stored_username():

try:

with open(filename, 'r') as f:

username = json.load(f)

except FileNotFoundError:

return None

else:

return username

def get_new_username():

username = input("What's your username? ")

with open(filename, 'w') as f:

json.dump(username, f)

return username

def check_username():

username = get_stored_username()

if username:

correct = input(f"Are you {username}? (y/n) ")

if correct.lower() == 'y':

return username

return get_new_username()

def greet_user():

username = check_username()

print(f"Welcome back, {username}!")

greet_user()

```

Remember to call `greet_user()` to start the whole shebang. Let me know if anything needs clearing up!

User Danneu
by
8.0k points