Module 7 – Chatbots & AI Helpers
intermediate30 XP

Build Your Own Q&A Bot in Python! πŸ› οΈ

Write a real working chatbot in Python using dictionaries and if-elif logic

Build Your Own Q&A Bot in Python! πŸ› οΈ

Your First Chatbot!

Let's build a simple question-and-answer chatbot. This is how early customer-service bots worked!

πŸ’‘

πŸ’‘ On this website, Python can't stop and wait for you to type. So instead, we give the bot a list of messages, as if someone typed them one by one. On your own computer, you could use input() to chat for real!

Version 1: Dictionary Bot πŸ“š

A dictionary matches each question to its answer, like a mini brain.

Python
knowledge_base = {
    "hello": "Hi there! I'm RoboBot. How can I help?",
    "what is ai": "AI stands for Artificial Intelligence: computers that can learn!",
    "tell me a joke": "Why don't scientists trust atoms? Because they make up everything!",
    "bye": "Goodbye! Keep coding!",
}

messages = ["hello", "what is ai", "what's your favorite pizza", "bye"]

for message in messages:
    print("You:", message)
    if message in knowledge_base:
        print("RoboBot:", knowledge_base[message])
    else:
        print("RoboBot: Hmm, I don't know that one yet!")

The bot only understands questions typed exactly the way it learned them. That's why early chatbots felt a bit... robotic. πŸ€–

Version 2: Smarter Keyword Detection 🧠

Instead of matching the whole sentence, look for keywords anywhere in it:

Python
def get_response(message):
    message = message.lower()
    if "joke" in message:
        return "Why did the computer go to the doctor? It had a virus!"
    elif "weather" in message or "rain" in message:
        return "I can't see outside, but a weather app can! It uses AI to predict rain."
    elif "name" in message:
        return "I'm RoboBot 3000, the friendliest chatbot!"
    else:
        return "Interesting! I'm still learning. Ask me for a joke!"

for message in ["What's your name?", "Will it RAIN today?", "Tell me a joke please"]:
    print("You:", message)
    print("RoboBot:", get_response(message))

Now "Will it RAIN today?" works, even with capitals, because .lower() makes everything lowercase first.

πŸ’‘

🧠 Real AI chatbots like ChatGPT don't use a list of keywords. They learned patterns from huge amounts of text. But the idea is the same: read the message β†’ pick a good reply.

πŸ† Challenge ideas

  1. Add a favorite color keyword.
  2. Add a fun fact reply when the message has "fact" in it.
  3. Give your bot its own name and personality!
⌨️

Type it yourself

Don't just read it β€” type the example from above into the box, press Run β–Ά, and watch what happens. Typing it yourself is how it really sticks! Stuck? Tap Show example.

Python Β· Playground
Output
Press β–Ά Run to see your code come to life…

Quick check

01/5
In the dictionary chatbot, what happens when the user asks something not in the knowledge_base?