Creating a simple chat bot in Python can be a fun and educational project. For this example, we’ll build a text-based chatbot that can perform simple conversational tasks like greeting the user and answering frequently asked questions. We’ll use Python’s built-in input
and print
functions for interaction.
Table of Contents
Requirements
- Python installed on your computer
Steps to Build the Chatbot
Step 1: Create a Greeting Function
First, create a function to greet the user based on the time of day.
from datetime import datetime
def greet_user():
current_hour = datetime.now().hour
if current_hour < 12:
return "Good morning!"
elif 12 <= current_hour < 18:
return "Good afternoon!"
else:
return "Good evening!"
Step 2: Create a Function to Handle User Input
Create a function to read user input and respond based on predefined keywords.
def handle_input(user_input):
user_input = user_input.lower()
if "hello" in user_input or "hi" in user_input:
return "Hello! How can I assist you?"
elif "how are you" in user_input:
return "I'm just a program, so I don't have feelings. But thanks for asking!"
elif "bye" in user_input:
return "Goodbye! Have a great day!"
else:
return "I'm sorry, I don't understand that."
Step 3: Main Loop for Conversation
Finally, create a loop to continuously interact with the user until they say “bye”.
if __name__ == "__main__":
print(greet_user())
while True:
user_input = input("You: ")
response = handle_input(user_input)
print(f"Bot: {response}")
if "goodbye" in response.lower():
break
Complete Code
Putting it all together, here’s the complete code for our simple Python chatbot:
from datetime import datetime
# Function to greet user based on time
def greet_user():
current_hour = datetime.now().hour
if current_hour < 12:
return "Good morning!"
elif 12 <= current_hour < 18:
return "Good afternoon!"
else:
return "Good evening!"
# Function to handle user input
def handle_input(user_input):
user_input = user_input.lower()
if "hello" in user_input or "hi" in user_input:
return "Hello! How can I assist you?"
elif "how are you" in user_input:
return "I'm just a program, so I don't have feelings. But thanks for asking!"
elif "bye" in user_input:
return "Goodbye! Have a great day!"
else:
return "I'm sorry, I don't understand that."
# Main function
if __name__ == "__main__":
print(greet_user())
while True:
user_input = input("You: ")
response = handle_input(user_input)
print(f"Bot: {response}")
if "goodbye" in response.lower():
break
To run this chatbot, save the code in a Python file and execute it. The bot will greet you and wait for your input. It will respond based on the keywords in your messages and will continue the conversation until you say “bye”.