Simple Chatbot using if-else and Pattern Matching
IntermediateBuild an interactive chatbot with Python's conditional logic
1) Project Overview
This project involves building a simple rule-based chatbot using if-else statements and pattern matching.
The chatbot can greet users, answer simple questions, and respond appropriately to known phrases.
π‘ Why it's useful: Chatbots are widely used in customer service, websites, and mobile apps. This project helps learners understand the logic behind chatbot communication without AI or machine learning, focusing instead on string processing, conditional logic, and user interaction.
2) Learning Objectives
By completing this project, learners will master:
| Concept | Description |
|---|---|
| String Handling | Learn to process and analyze user input using string methods |
| Conditional Logic | Use if-elif-else for decision-making based on user messages |
| Pattern Matching | Understand how to match user phrases using keywords |
| Looping Structures | Keep the chatbot running in a loop until the user exits |
| Functions | Organize chatbot responses into reusable blocks of code |
| Basic NLP Logic | Implement simple keyword-based logic β the foundation of natural language processing |
3) Step-by-Step Explanation
Follow these steps to build the chatbot:
- Project Setup β Create a new Python file named chatbot.py. You'll build a text-based chatbot that greets the user, responds to simple questions (like name, time, weather, etc.), and says goodbye when the user types "bye"
- Import Required Modules β We'll use Python's built-in datetime module to tell the current time
- Define Chatbot Responses β We'll use if-elif conditions to check user input and generate responses
- Add Basic Pattern Matching β We'll use keyword checking (using the in operator) to match user queries even if the sentence varies slightly β for example: "hi", "hello", "hey" β all count as greetings
- Create a Conversation Loop β The chatbot will continuously take user input, respond based on patterns, and exit when the user types "bye"
- Display Friendly Messages β Make the chatbot interactive and human-like by adding a welcome message, small delays (optional), and proper formatting
4) Complete, Well-Commented, and Verified Python Code
Save the following as chatbot.py:
# ------------------------------------------------------------
# π€ Simple Chatbot using if-else and Pattern Matching
# Author: Your Name
# Level: Intermediate
# Verified: Python 3.8+
# ------------------------------------------------------------
import datetime
def get_current_time():
"""Return the current system time in HH:MM format."""
now = datetime.datetime.now()
return now.strftime("%H:%M")
def chatbot_response(user_input):
"""Generate chatbot responses based on user input."""
user_input = user_input.lower() # convert input to lowercase for pattern matching
# Greetings
if "hi" in user_input or "hello" in user_input or "hey" in user_input:
return "Hello there! π How can I help you today?"
# Asking name
elif "your name" in user_input:
return "I'm ChatPy β your friendly Python chatbot!"
# Asking about chatbot's origin
elif "who made you" in user_input or "created you" in user_input:
return "I was created by a Python programmer who loves teaching code. π§ "
# Asking current time
elif "time" in user_input:
current_time = get_current_time()
return f"The current time is {current_time}."
# Asking about weather
elif "weather" in user_input:
return "I can't check the weather yet π¦οΈ, but you can look outside or try an online weather app."
# Asking how chatbot is
elif "how are you" in user_input:
return "I'm just a bunch of Python code, but I'm doing great! How about you?"
# User replies they're fine
elif "fine" in user_input or "good" in user_input:
return "Glad to hear that! π"
# Asking what chatbot can do
elif "help" in user_input or "can you do" in user_input:
return ("I can chat with you, tell the current time, and answer basic questions. "
"Soon, I might even tell jokes! π")
# Exit condition
elif "bye" in user_input or "exit" in user_input or "quit" in user_input:
return "Goodbye! π Have a nice day."
# Default fallback response
else:
return "Hmm, I'm not sure I understand that. Try asking something else."
def main():
"""Main chatbot program loop."""
print("===========================================")
print("π€ Welcome to ChatPy β Your Python Chatbot!")
print("Type 'bye' anytime to exit.")
print("===========================================\n")
while True:
user_input = input("You: ")
response = chatbot_response(user_input)
print("ChatPy:", response)
if "bye" in user_input.lower():
break
# Run the chatbot
if __name__ == "__main__":
main()
β’ Runs without errors in Python 3.8+
β’ Uses pattern matching and conditional logic
β’ Gracefully exits when "bye" or "exit" is typed
β’ Provides context-aware responses
5) Output Example (Sample Run)
π€ Welcome to ChatPy β Your Python Chatbot!
Type 'bye' anytime to exit.
===========================================
You: hello
ChatPy: Hello there! π How can I help you today?
You: what's your name?
ChatPy: I'm ChatPy β your friendly Python chatbot!
You: what time is it?
ChatPy: The current time is 14:37.
You: how are you?
ChatPy: I'm just a bunch of Python code, but I'm doing great! How about you?
You: I'm fine
ChatPy: Glad to hear that! π
You: bye
ChatPy: Goodbye! π Have a nice day.
6) Extension Challenge
π― Ideas to make it more advanced
Goal: Enhance your chatbot with these features:
- Add Jokes or Facts Feature: Use the random module to pick and display random jokes or fun facts
- Integrate a Weather API: Use the requests library and OpenWeatherMap API to fetch real-time weather
- Add a GUI Interface: Use tkinter to create a simple chatbot window with text input and chat bubbles
- Use Regular Expressions: Replace manual keyword checking with the re module for smarter pattern matching
- Save Conversation Logs: Write chat history to a text file for record-keeping
7) Summary
π You just built a Simple Chatbot using:
- Conditional logic (if-else)
- String pattern matching
- Functions and loops
- Basic use of libraries (datetime)
This project gives learners a strong understanding of how chatbots interpret user input before using advanced tools like NLTK or AI APIs.
π¬ "Every complex AI chatbot begins as a few if-else statements!"