🧠What You’ll Learn
In this post, you’ll build a simple yet smart Python chatbot that can understand variations and typos in user input using just the difflib
module—no AI libraries required!
This chatbot isn’t just based on if-else
logic; it matches close sentences to known responses. Even if the user types “helo” instead of “hello,” it will still work!
The Code
import difflib
known_inputs = {
"hello": 'Hi, How can I help you?',
"hi": 'Hi, How can I help you?',
"What's your name": "I'm a Python ChatBot",
"bye": "Bye. Have a nice day"
}
while True:
user_input = input('You : ').lower()
key = difflib.get_close_matches(user_input, known_inputs.keys(), n=1, cutoff=0.5)
if key:
key = key[0]
if key == 'bye':
break
print("Bot :", known_inputs[key])
else:
print("Bot : Sorry. I didn't understand that. I'm still learning.")
🔍 How It Works
difflib.get_close_matches()
: This function helps match the user input to the closest key in our chatbot dictionary. Even if a user types slightly incorrect text (like a typo), it finds the best possible match.cutoff=0.5
: This means the input must be at least 50% similar to a known input to be considered.- Graceful exit: If the user says “bye”, the bot ends the conversation.
📽️ Watch It in Action!
👉 Check out the full video tutorial here:
đź”” Like what you see?
âś… Subscribe to my YouTube channel for more Python + AI videos:
https://www.youtube.com/@EverythingAboutCoding