0%
⭐ 0 XPMap
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

  1. Make load_memory(): return the dict saved in memory.json, or {} if there's no file yet.
  2. Make save_memory(mem) that writes mem to memory.json with json.dump.
  3. Chat 1: load the memory, set "name" to "Sam", and save it.
  4. 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"].

Ask the community

bot.py
Terminal
← BackNext →

Chapter 4: Memory

The full quest map

Talk it out

  1. Read the instruction with the ✗ out loud.
  2. Say what your code does, line by line, as if to a friend.
  3. Find the line where what it does and what you want split apart.
  4. Press Run and read the terminal. Is that what you expected?
  5. Still stuck? Press Ask Pip why, or peek at the solution.
  6. Or ask on the community help board: say which quest, and paste your code.
New badge!

Your bot just got a new part. See it on the quest map.

Name your bot

It levels up as you play, and gets a new part with every chapter.