Chapter 4 · Quest 5 of 5 · 15 XP
Pen Pal
💌 Last quest of the chapter: a bot that remembers a friend between chats. Save the memory as JSON in a file at the end of one chat, and load it at the start of the next.
import json
with open("save.json", "w") as f:
json.dump({"level": 3}, f)
with open("save.json") as f:
print(json.load(f)){'level': 3}"w" writes the file fresh. The very first time there's no file yet, so check with os.path.exists() before you open it. Finish this one for the Elephant badge.
Instructions
- Make
load_memory(): return the dict saved inmemory.json, or{}if there's no file yet. - Make
save_memory(mem)that writesmemtomemory.jsonwithjson.dump. - Chat 1: load the memory, set
"name"to"Sam", and save it. - Chat 2: load it again and print
Welcome back, Sam!using the saved name.
💡 Hint
load_memory: if not os.path.exists("memory.json"): return {}. Otherwise open it and return json.load(f). In chat 2, build the message with + and mem["name"].
bot.py
Terminal