Creating a simple AI program in Python can be fun! For this example, let's create a basic chatbot that can respond to user inputs. This chatbot will use simple pattern matching to generate responses.
Here's a simple Python program using a while loop for interaction. You can run this on PythonAnywhere:
# chatbot.py
def chatbot_response(user_input):
user_input = user_input.lower()
if "hello" in user_input:
return "Hello! How can I help you today?"
elif "how are you" in user_input:
return "I'm just a program, but thanks for asking! How about you?"
elif "your name" in user_input:
return "I am a simple chatbot created to assist you."
elif "bye" in user_input:
return "Goodbye! Have a great day!"
else:
return "I'm sorry, I don't understand that."
def main():
print("Welcome to the chatbot! Type 'bye' to exit.")
while True:
user_input = input("You: ")
if user_input.lower() == "bye":
print(chatbot_response(user_input))
break
response = chatbot_response(user_input)
print("Chatbot:", response)
if __name__ == "__main__":
main()
Instructions to Run the Program on PythonAnywhere
-
Sign in to PythonAnywhere: Go to pythonanywhere.com and log in or create an account.
-
Create a new file:
- Go to the "Files" tab.
- Click on "New file".
- Name the file
chatbot.py
.
-
Copy the code above:
- Paste the code into the newly created file and save it.
-
Run the program:
- Open a new Bash console from the "Consoles" tab.
- In the console, navigate to the directory where you saved the
chatbot.py
file (if necessary). - Run the program by typing:
python3 chatbot.py
-
Interact with the chatbot: You can now type in your messages, and the chatbot will respond accordingly.
Notes
- Make sure you use Python 3 when running the program since the print function syntax and input handling are suited for Python 3.
- This chatbot is quite simple and does not use any machine learning; it's based on keyword matching. You can expand it by adding more patterns or integrating with libraries like NLTK or a pre-trained model if you want to go deeper into AI.