Build a Mini Chatbot
Explore how to build a mini chatbot in Python by applying key concepts such as functions, conditionals, input handling, loops, and string operations. This lesson helps you develop an interactive program that responds intelligently to user input and continues the conversation until a goodbye is detected.
We'll cover the following...
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()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()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()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.