Learning Hub/AI App Development/Session 3

Session 3 of 5 · 60 minutes

Building a Chat Loop

Use a while loop and a function to build a chatbot that remembers the conversation.

Goals

By the end of this session you can:

  • Build a chat loop that reads user input until the user types quit
  • Write a get_reply() function that decides how the bot answers
  • Keep the conversation history in a list
  • Explain why the reply function is easy to swap for a real AI model later

Words to know

chat loop
A loop that keeps asking the user for a message and printing a reply.
history
A list of everything said so far in the conversation.
rule-based bot
A bot that picks its reply with if statements instead of a trained model.
keyword
A word the bot looks for in the user's message.

The lesson

Step 1: The chat loop

A chatbot is a loop. It reads a message, decides on a reply, prints it, and repeats.

Python
def get_reply(message):
    return "You said: " + message

while True:
    message = input("You: ")
    if message == "quit":
        print("Bot: Goodbye!")
        break
    print("Bot:", get_reply(message))
Output
You: hello
Bot: You said: hello
You: nice day
Bot: You said: nice day
You: quit
Bot: Goodbye!

Notice we put the decision-making in its own function, get_reply. The loop doesn’t care how the reply is made. That will matter in a moment.

Step 2: Deciding how to reply

A rule-based bot looks for keywords and picks a reply with if statements.

Python
def get_reply(message):
    text = message.lower()
    if "hello" in text or "hi" in text.split():
        return "Hello! How can I help you study?"
    if "help" in text:
        return "Try typing 'quiz' and I'll ask you a question."
    if "thanks" in text:
        return "You're welcome!"
    return "I'm not sure about that. Type 'help' to see what I can do."

print(get_reply("Hello there"))
print(get_reply("can you HELP me"))
print(get_reply("what is a volcano"))
Output
Hello! How can I help you study?
Try typing 'quiz' and I'll ask you a question.
I'm not sure about that. Type 'help' to see what I can do.

.lower() turns the message into lowercase so capital letters don’t matter. The last line is a fallback: what the bot says when it doesn’t understand. Good bots always have a polite fallback.

Step 3: Remembering the conversation

A chat is more than one message. A real AI model uses what was said earlier to answer follow-up questions. We store the conversation in a list, called a history.

Python
history = []

history.append({"who": "user", "text": "Hi!"})
history.append({"who": "bot", "text": "Hello!"})
history.append({"who": "user", "text": "Tell me a fact."})

print(len(history), "messages so far")
for turn in history:
    print(turn["who"] + ":", turn["text"])
Output
3 messages so far
user: Hi!
bot: Hello!
user: Tell me a fact.

In your chat loop, append each user message and each bot reply to the history. Then pass the history to the reply function so it can use it later:

Python
def get_reply(message, history):
    if len(history) == 0:
        return "Nice to meet you!"
    return "We've been chatting for " + str(len(history)) + " messages."

Step 4: A quiz mode

Chatbots can have modes. Here is a small quiz mode that keeps score.

Python
questions = [
    {"q": "What is 7 x 8?", "a": "56"},
    {"q": "What is the capital city of Tanzania?", "a": "dodoma"},
]

score = 0
for item in questions:
    answer = input(item["q"] + " ")
    if answer.strip().lower() == item["a"]:
        print("Correct!")
        score += 1
    else:
        print("Not quite. The answer is", item["a"])

print("Score:", score, "out of", len(questions))
Output
What is 7 x 8? 56
Correct!
What is the capital city of Tanzania? dar es salaam
Not quite. The answer is dodoma
Score: 1 out of 2

.strip() removes extra spaces and .lower() ignores capitals, so ” Dodoma ” counts as correct.

Step 5: Why this matters

Your bot works with if statements. A real AI model replaces the if statements: instead of keywords, a model reads the whole message and writes a reply.

But your app around it stays almost the same: a loop, a history, a function that returns a reply. Next session we’ll connect get_reply() to a real model, safely.

Exercise

Teach the bot three new tricks

  1. Start from the chat loop in the lesson.
  2. Add a new keyword reply: if the message contains joke, the bot tells a short, kind joke.
  3. Add one more keyword of your choice, such as weather or school.
  4. Make the bot print how many messages have been sent when you type quit.
Need a hint?

Use if "joke" in message.lower(): so it works with capital letters too.

Small project

Study buddy bot

Build a rule-based chatbot that helps you study. It can greet, quiz you from a list of questions, and keep score.

  1. Create a list of at least four questions and answers (a list of dictionaries works well).
  2. Write get_reply(message, history) that returns a reply based on keywords like hello, quiz and help.
  3. In quiz mode, ask a question, check the user's answer ignoring capital letters, and update the score.
  4. Print the score and how many messages were sent when the user types quit.
  5. Test with a classmate and fix the one thing that confused them most.

Stretch it: Save the conversation to a text file with open("chat.txt", "w") when the user quits.

Quiz

Check your understanding

Pick one answer for each question. Your score appears right in the page; nothing is sent anywhere.

  1. Question 1What does a chat loop do?
  2. Question 2Why put the bot's logic in a function like get_reply()?
  3. Question 3What does message.lower() do?
  4. Question 4What is the history list for?
  5. Question 5Which check makes the loop stop?