Build a Mini Chatbot

Learn how to create a chatbot using loops and decision logic.

Let’s use all your Python powers to create a simple chatbot—a program that interacts!

You’ll use functions, conditionals, input, loops, and string handling—everything you’ve practiced.

Step 1: Say hello

Let’s start by greeting the user:

def chatbot():
    print("Hi! I'm ChatPy. Let's talk!")
    name = input("What's your name? ")
    print("Nice to meet you", name, "!")

chatbot()
Starting a chatbot conversation and greeting the user

The bot is already interactive!

Step 2: Keep the conversation going

Now, let’s create a loop so it can keep chatting:

def chatbot():
    print("Hi! I'm ChatPy. Type 'bye' to end the chat.")
    
    while True:
        message = input("You: ")
        if message == "bye":
            print("ChatPy: Goodbye!")
            break
        print("ChatPy: You said:", message)

chatbot()
Adding a loop so the chatbot keeps responding until we say “bye”

Now it responds forever—until we say bye.

Step 3: Add some personality

Let’s teach it some smart replies:

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 "how are you" in msg:
            print("ChatPy: I'm just code, but I feel awesome!")
        elif "name" in msg:
            print("ChatPy: I'm ChatPy, your Python buddy.")
        else:
            print("ChatPy: Interesting!")

chatbot()
Using conditionals to give the chatbot more expressive responses

The in keyword in Python is a very versatile operator and can be used in different contexts, especially when working with sequences like strings, lists, or even dictionaries.

Here, we’ve used in in an if statement to check whether a value exists in a sequence (like here, to see if the phrase "how are you" is inside the user’s message).

Try it! Our chatbot now reacts differently based on what we say.