From cca2d5153dab8da4a9a87fecebd42e766bee9346 Mon Sep 17 00:00:00 2001 From: cheeks <134818917+leftovertoast@users.noreply.github.com> Date: Sun, 9 Mar 2025 21:34:05 +0000 Subject: [PATCH] Completed 10-13 User Dictionary --- Chapter_10/10-13_user_dictionary.py | 45 +++++++++++++++++++++++++++++ user_info.json | 1 + 2 files changed, 46 insertions(+) create mode 100644 Chapter_10/10-13_user_dictionary.py create mode 100644 user_info.json diff --git a/Chapter_10/10-13_user_dictionary.py b/Chapter_10/10-13_user_dictionary.py new file mode 100644 index 0000000..a50ed84 --- /dev/null +++ b/Chapter_10/10-13_user_dictionary.py @@ -0,0 +1,45 @@ +# Exercise 10-13 User Dictioinary +# Learning Objective: Save/Load json using json dumps/loads. + +from pathlib import Path +import json + +def get_stored_info(path): + """Get stored username if available.""" + if path.exists(): + contents = path.read_text() + information = json.loads(contents) + return information + else: + pass + +def get_information(path): + """Prompt for information.""" + data = { + + } + username = input("What is your name? ") + location = input("What country/state are you in? ") + age = input("How old are you? ") + data["username"] = username + data["location"] = location + data["age"] = age + save_data = json.dumps(data) + path.write_text(save_data) + return data + + +def greet_user(): + """Greet the user by name.""" + path = Path('user_info.json') + information = get_stored_info(path) + if information: + print(f"Welcome back, {information["username"]}! We remember that you are from {information["location"]} and that you are {information["age"]} years old since the last time you ran this.") + else: + entered_data = get_information(path) + print(f"We'll remember this information for when you come back, \n") + for i in entered_data: + print(f"{entered_data[i]}") + +greet_user() + diff --git a/user_info.json b/user_info.json new file mode 100644 index 0000000..97c6fce --- /dev/null +++ b/user_info.json @@ -0,0 +1 @@ +{"username": "Steve", "location": "CZ", "age": "32"} \ No newline at end of file