computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

💬

🎓

⏱ 35 min

Free

Project: Build a Chatbot

Put it all together: match what someone says to a reply, then add a safety rule.

🎯 What you will learn

  • A chatbot matches input to replies
  • Fallback replies handle the unknown
  • Safety rules come before clever replies

👋 Let’s get started!

Let’s build a chatbot! It matches words in a message to a reply. When it does not know, it asks for help from a trusted grown-up. Real chatbots are far bigger, but they still follow the same ideas. 💬

🪜 Step by step

1. 📖 Replies

A dictionary connects a keyword to a reply.

replies = {"hello": "Hi there!", "game": "Try Spot the Scam!"}
2. 🔍 Find a keyword

Loop through the words in the message and look for a match.

for word in message.split():
    if word in replies:
        print(replies[word])
3. 🛡️ Safety first

If someone asks for a password or address, the bot always says no.

if "password" in message:
    print("Never share passwords. Ask a grown-up.")

🧪 Try it!

Change the code and press ▶ Run to see what happens. You can’t break anything!

Chatbot demo

replies = {"hello": "Hi there!", "game": "Try Spot the Scam!"}
def answer(message):
    if "password" in message:
        return "Never share passwords. Ask a grown-up."
    for word in message.split():
        if word in replies:
            return replies[word]
    return "I am not sure. Ask a trusted grown-up!"
print(answer("hello there"))
print(answer("what game should I play"))
print(answer("what is my password"))
print(answer("tell me a joke"))

🎨 Unplugged activity

💬 Add two new keywords and replies to the chatbot, plus a safety rule of your own. Test five messages, including one with a tricky word, and explain each answer to a grown-up.

Fix the chatbot

def answer(message):
    for word in message.split():
        if word in replies:
            return replies[word]
    return "Ask a grown-up"

📖 Key words

Tap a card to flip it over!

Chatbot
A program that replies to messages 💬
Keyword
A word the bot looks for 🔑
Fallback
The reply when nothing matches 🛟

🏆 Challenge

Make answer(“hi game”) return the game reply. Make the bot print the result. Press ▶ Run.

Challenge

replies = {"hello": "Hi there!", "game": "Try Spot the Scam!"}
def answer(message):
    for word in message.split():
        if word in replies:
            return replies[word]
    return "Ask a grown-up"

Knowledge Check Quiz

  1. What does the chatbot do when nothing matches?
  2. Why check for “password” first?
  3. What is a keyword?
← Previous lesson