0% found this document useful (0 votes)
3 views1 page

User Greeting and Storage Functions

Uploaded by

darkflux514
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

User Greeting and Storage Functions

Uploaded by

darkflux514
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

if path.

exists():
contents = path.read_text()
username = [Link](contents)
return username
else:
2 return None

def greet_user():
"""Greet the user by name."""
path = Path('[Link]')
username = get_stored_username(path)
3 if username:
print(f"Welcome back, {username}!")
else:
username = input("What is your name? ")
contents = [Link](username)
path.write_text(contents)
print(f"We'll remember you when you come back, {username}!")

greet_user()

The new function get_stored_username() 1 has a clear purpose, as stated


in the docstring. This function retrieves a stored username and returns the
username if it finds one. If the path that’s passed to get_stored_username()
doesn’t exist, the function returns None 2. This is good practice: a function
should either return the value you’re expecting, or it should return None.
This allows us to perform a simple test with the return value of the func-
tion. We print a welcome back message to the user if the attempt to retrieve
a username is successful 3, and if it isn’t, we prompt for a new username.
We should factor one more block of code out of greet_user(). If the user-
name doesn’t exist, we should move the code that prompts for a new username
to a function dedicated to that purpose:

from pathlib import Path


import json

def get_stored_username(path):
"""Get stored username if available."""
--snip--

def get_new_username(path):
"""Prompt for a new username."""
username = input("What is your name? ")
contents = [Link](username)
path.write_text(contents)
return username

def greet_user():
"""Greet the user by name."""
path = Path('[Link]')
1 username = get_stored_username(path)
if username:
print(f"Welcome back, {username}!")

Files and Exceptions 205

You might also like