Search⌘ K
AI Features

Solution: Custom Responses

Explore how to create a text-based chatbot in Python that responds uniquely based on user inputs like keywords or phrases. Learn to implement conditional logic, manage an interactive loop, and handle different user messages to build engaging, real-world chat programs.

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