Aucune description

remember_me.py 809B

1234567891011121314151617181920212223242526272829303132
  1. import json
  2. def get_stored_username():
  3. """Get stored username if available."""
  4. filename = 'username.json'
  5. try:
  6. with open(filename) as f_obj:
  7. username = json.load(f_obj)
  8. except FileNotFoundError:
  9. return None
  10. else:
  11. return username
  12. def get_new_username():
  13. """Prompt for a new username."""
  14. username = input("What is your name? ")
  15. filename = 'username.json'
  16. with open(filename, 'w') as f_obj:
  17. json.dump(username, f_obj)
  18. return username
  19. def greet_user():
  20. """Greet the user by name."""
  21. username = get_stored_username()
  22. if username:
  23. print("Welcome back, " + username + "!")
  24. else:
  25. username = get_new_username()
  26. print("We'll remember you when you come back, " + username + "!")
  27. greet_user()