Search⌘ K
AI Features

Solution: Custom Responses

Explore how to create a simple Python chatbot that interacts through the console by responding differently to keywords like food and jokes. Learn to implement conversation loops and custom replies, enabling you to build fun, interactive chat programs with basic Python syntax.

We'll cover the following...

This program defines a simple text-based chatbot called ChatPy that interacts with the user through the console. When the program starts, it greets the user and enters an infinite loop to keep the conversation going. Inside the loop, it waits for user input and responds based on what the user types. If the message contains the word “food”, ChatPy replies with a playful message about “binary bites.” If it contains “joke”, it tells a programming-related joke. If the user types “bye”, the chatbot says goodbye and exits the loop, effectively ending the chat. For any other input, ChatPy gives a general response encouraging the user to continue.

def chatbot():
    print("Hi! I'm ChatPy. Let's chat. Type 'bye' to exit.")

    while True:
        msg = input("You: ")

        if msg == "bye":
            print("ChatPy: See you later!")
            break
        elif "food" in msg:
            print("ChatPy: I love binary bites!")
        elif "joke" in msg:
            print("ChatPy: Why did the Python break up with the loop? It had too many issues!")
        else:
            print("ChatPy: Interesting... Tell me more!")

chatbot()
Adding custom responses to make the chatbot more fun and engaging