w3resource

Python Project - Simple Chatbot Solutions and Explanations


Basic Chatbot:

Create a simple chatbot that responds to user input with predefined answers.

Input values:
Input or questions are provided by the user to the chatbot.

Output value:
Predefined responses generated by the chatbot.

Example:

Input values:
User: How are you?
Output value:
Chatbot: I'm doing well, thank you!

Here are two different solutions for a basic chatbot in Python. The chatbot will respond to user input with predefined answers.

Solution 1: Basic Chatbot using Conditional Statements

Code:

 # Solution 1: Basic Chatbot Using Conditional Statements

def chatbot_response(user_input):
    """Function to provide predefined responses based on user input"""
    # Convert the user input to lowercase to handle different cases
    user_input = user_input.lower()

    # Provide predefined responses based on user input using conditional statements
    if "hello" in user_input or "hi" in user_input:
        return "Hello! How can I help you today?"
    elif "how are you" in user_input:
        return "I'm doing well, thank you!"
    elif "what is your name" in user_input:
        return "I'm a simple chatbot, and I don't have a name yet!"
    elif "bye" in user_input or "goodbye" in user_input:
        return "Goodbye! Have a great day!"
    else:
        return "I'm sorry, I don't understand. Can you please rephrase?"

# Main loop to interact with the user
print("Welcome to the chatbot! Type 'bye' to exit.")
while True:
    # Get input from the user
    user_input = input("User: ")

    # If the user types 'bye', exit the chat
    if user_input.lower() == "bye":
        print("Chatbot: Goodbye! Have a great day!")
        break

    # Get the chatbot's response
    response = chatbot_response(user_input)
    print(f"Chatbot: {response}")

Output:

Welcome to the chatbot! Type 'bye' to exit.
User: Hello
Chatbot: Hello! How can I help you today?
User: How are you?
Chatbot: I'm doing well, thank you!
User: bye
Chatbot: Goodbye! Have a great day!

Explanation:

  • The chatbot logic is handled by a function 'chatbot_response()' that checks the user's input against predefined phrases using conditional statements ('if-elif').
  • If a match is found, the corresponding response is returned; otherwise, a default response is provided.
  • The chatbot runs in a 'while' loop, allowing continuous interaction with the user until the user types "bye" to exit.
  • This approach is simple and easy to understand, but it can become cumbersome to maintain if many responses are added.

Solution 2: Using a Dictionary-Based approach for Chatbot Responses

Code:

# Solution 2: Using a Dictionary-Based Approach for Chatbot Responses

class SimpleChatbot:
    """Class to handle chatbot interactions"""

    def __init__(self):
        """Initialize the chatbot with predefined responses"""
        # Define predefined responses in a dictionary
        self.responses = {
            "hello": "Hello! How can I help you today?",
            "hi": "Hello! How can I help you today?",
            "how are you": "I'm doing well, thank you!",
            "what is your name": "I'm a simple chatbot, and I don't have a name yet!",
            "bye": "Goodbye! Have a great day!",
            "goodbye": "Goodbye! Have a great day!"
        }

    def get_response(self, user_input):
        """Get a response from the chatbot based on user input"""
        # Convert the user input to lowercase and remove leading/trailing whitespace
        user_input = user_input.lower().strip()

        # Check if the user input matches any predefined responses
        for key in self.responses:
            if key in user_input:
                return self.responses[key]

        # Default response if the input is not recognized
        return "I'm sorry, I don't understand. Can you please rephrase?"

    def start_chat(self):
        """Start the chatbot interaction with the user"""
        print("Welcome to the chatbot! Type 'bye' to exit.")
        while True:
            # Get input from the user
            user_input = input("User: ")

            # If the user types 'bye', exit the chat
            if user_input.lower() == "bye":
                print("Chatbot: Goodbye! Have a great day!")
                break

            # Get the chatbot's response
            response = self.get_response(user_input)
            print(f"Chatbot: {response}")

# Create an instance of the SimpleChatbot class
chatbot = SimpleChatbot()

# Start the chatbot interaction
chatbot.start_chat()

Output:

Welcome to the chatbot! Type 'bye' to exit.
User: Hello
Chatbot: Hello! How can I help you today?
User: How are you?
Chatbot: I'm doing well, thank you!
User: What is your name?
Chatbot: I'm a simple chatbot, and I don't have a name yet!
User: bye
Chatbot: Goodbye! Have a great day!

Explanation:

  • Defines a SimpleChatbot class to handle all chatbot functionality, making the code more organized and modular.
  • The predefined responses are stored in a dictionary (self.responses), with keys representing trigger phrases and values representing responses.
  • The get_response() method iterates over the dictionary keys to find a match in the user input and returns the corresponding response.
  • The start_chat() method manages the interaction loop, allowing the user to continue chatting until they type "bye".
  • This approach is more scalable and maintainable, as new responses can easily be added or modified in the dictionary.

Note:
Both solutions provide a basic chatbot that responds to user input with predefined answers, with Solution 1 offering a functional, straightforward approach and Solution 2 using a more structured, class-based implementation for better organization and extensibility.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/projects/python/python-basic-chatbot-project.php