Introduction
Chatbots have become an integral part of digital communication. They can handle a wide variety of tasks, from customer service inquiries to fun and interactive experiences. In this guide, we will create a simple chatbot using Python, which will respond to user input. The chatbot will be able to interact in a very basic way, offering predefined responses based on the user’s input.
Objective
The goal of this exercise is to build a simple chatbot program that:
- Greets the user when they start the conversation.
- Responds to basic questions such as “How are you?” or “What is your name?”.
- Exits when the user types “bye” or “exit”.
Python Chatbot Code
import random
def chatbot():
print("Hello! I'm a simple chatbot. Type 'bye' to end the conversation.")
while True:
user_input = input("You: ").lower()
if user_input in ['bye', 'exit']:
print("Goodbye! Have a great day.")
break
elif user_input in ['how are you?', 'how are you doing?', 'how's it going?']:
responses = ["I'm doing well, thank you!", "I'm great, how about you?", "I'm doing just fine, how can I help?"]
print("Bot: " + random.choice(responses))
elif user_input in ['what is your name?', 'who are you?']:
print("Bot: My name is ChatBot!")
else:
print("Bot: I'm sorry, I didn't understand that.")
if __name__ == "__main__":
chatbot()
Explanation of the Program
The program is structured as follows:
- The
chatbot
function handles the interaction with the user. It continuously prompts the user for input until the user types “bye” or “exit”. - The program processes the user’s input using a
while
loop, which keeps running until a break condition is met (i.e., the user types “bye” or “exit”). - It checks if the user’s input matches any predefined phrases like “How are you?” or “What is your name?” and responds with a random selection from a list of responses for “How are you?”.
- If the user’s input is not recognized, the bot replies with a default message, saying it didn’t understand the input.
- The
random.choice()
function is used to pick a random response from a predefined list of responses for a given input.
How to Run the Program
To run the chatbot, follow these steps:
- Ensure that you have Python installed on your computer. You can download it from the official Python website.
- Create a new Python file, e.g., chatbot.py, and paste the code into this file.
- Open a terminal or command prompt and navigate to the directory where your chatbot.py file is saved.
- Run the script by typing
python chatbot.py
in the terminal and press Enter. - The chatbot will start, and you can begin interacting with it by typing your input.