Build a Chatbot in Python: Step-by-Step Project with Source Code (Free PDF)

Updated October 2026 | 16 min read
A chatbot is the best first AI project you can build in Python. It’s small enough to finish in an afternoon, it’s genuinely useful, and it teaches you how real systems understand language — without needing a GPU, an API key, or a maths degree. In this guide you’ll build a chatbot in Python three times, each version about ten minutes, each one smarter than the last:
- Version 1 — Rule-based (20 lines): keywords in, replies out. Every chatbot started here.
- Version 2 — Fuzzy matching (+10 lines): handles typos like “helo” and “thnks.”
- Version 3 — Intent-based AI (~40 lines + a JSON file): a real NLTK + scikit-learn model that classifies what the user means, trained on your own examples.
All three run in a terminal, all three have real output below, and the full source code plus a PDF of these notes is free at the end. If you’ve been through our Data Science with Python notes, Version 3 will feel familiar — it’s TF-IDF and logistic regression, applied to text. If you haven’t, no problem; every line is explained.
How a Chatbot Actually Works
Strip away the hype and every chatbot — from a 20-line script to ChatGPT — does three things in order:
- Take the user’s input — a string of text.
- Work out the intent — what does the user want? Greeting? Price? Opening hours?
- Pick a response for that intent and print it.

The three versions differ only in step 2. Version 1 checks for keywords. Version 2 checks for keywords approximately. Version 3 trains a model to predict the intent from examples. Step 1 and step 3 are the same loop every time — which is why once you’ve built Version 1, the other two are small upgrades, not rewrites.
Setup
You need Python 3.10 or newer. Version 1 and 2 use only the standard library. Version 3 needs two packages:
$ pip install nltk scikit-learn
Version 1 — Rule-Based Chatbot (20 Lines)
The simplest possible chatbot: a dictionary mapping keywords to replies, and a loop that checks whether any keyword appears in what the user typed.
rules = {
"hello": "Hello! How can I help you today?",
"hours": "We're open Monday to Friday, 9am to 6pm.",
"price": "Our courses start from Rs. 5,000.",
"course": "We offer Python, Data Science and ML courses.",
"thanks": "You're welcome!",
"bye": "Goodbye! Have a great day.",
}
print("TechBot v1 ready (type 'quit' to exit)")
while True:
user = input("You: ").lower()
if user == "quit":
break
reply = "Sorry, I don't understand that yet."
for keyword, response in rules.items():
if keyword in user:
reply = response
break
print("Bot:", reply)
You: hello
Bot: Hello! How can I help you today?
You: what are your hours?
Bot: We’re open Monday to Friday, 9am to 6pm.
You: how much is the python course
Bot: We offer Python, Data Science and ML courses.
You: helo
Bot: Sorry, I don’t understand that yet.
You: quit
It works — mostly. Look at the third exchange: the user asked how much the course costs, but the bot answered with the course list. Why? The input contains the word “course” and not the word “price,” so the keyword loop matched course. The bot answered the word, not the meaning — it has no idea that “how much” means price. Then “helo” is a typo, nothing matches, and the bot gives up entirely. Rule-based bots are fast and predictable, but brittle: every spelling and every phrasing has to be anticipated by you. Version 2 fixes the typo problem; Version 3 fixes the meaning problem.
Version 2 — Smarter Matching with difflib
Python’s standard library has difflib.get_close_matches, which finds the closest string from a list even if it’s misspelled. We’ll clean the input (lowercase, strip punctuation), split it into words, and fuzzy-match each word against our keywords.
import string
from difflib import get_close_matches
rules = {
"hello": "Hello! How can I help you today?",
"hours": "We're open Monday to Friday, 9am to 6pm.",
"price": "Our courses start from Rs. 5,000.",
"course": "We offer Python, Data Science and ML courses.",
"thanks": "You're welcome!",
"bye": "Goodbye! Have a great day.",
}
keywords = list(rules.keys())
def clean(text):
text = text.lower()
return text.translate(str.maketrans("", "", string.punctuation))
print("TechBot v2 ready (type 'quit' to exit)")
while True:
user = clean(input("You: "))
if user == "quit":
break
reply = "Sorry, I don't understand that yet."
for word in user.split():
match = get_close_matches(word, keywords, n=1, cutoff=0.6)
if match:
reply = rules[match[0]]
print(f" (matched '{word}' → '{match[0]}')")
break
print("Bot:", reply)
You: helo
(matched ‘helo’ → ‘hello’)
Bot: Hello! How can I help you today?
You: thnks!
(matched ‘thnks’ → ‘thanks’)
Bot: You’re welcome!
You: What are your HOURS?
(matched ‘your’ → ‘hours’)
Bot: We’re open Monday to Friday, 9am to 6pm.
You: quit
“helo” now matches “hello” and “thnks!” matches “thanks” — punctuation stripped, case ignored, typo forgiven. But look closely at the third exchange: the reply is right, yet the match line says 'your' → 'hours', not 'hours' → 'hours'. The loop reached the word “your” first, and difflib decided “your” is close enough to “hours” (they share o-u-r) to clear the 0.6 cutoff. We got lucky — it happened to land on the right keyword. Fuzzy matching is helpful but imprecise: raise cutoff to 0.8 and “your” stops matching, but so do some genuine typos. There’s no setting that’s right for every case, which is exactly why Version 3 replaces string similarity with real intent classification.
Version 3 — Intent-Based AI Chatbot with NLTK + scikit-learn
This is the real thing. Instead of keywords, we write a JSON file of intents: each intent has a name, several example phrases a user might type (patterns), and a few replies (responses). We train a classifier on the patterns. At runtime the model predicts the intent of whatever the user types — even phrasings it has never seen — and the bot replies with one of that intent’s responses.
Step 1 — The intents file
Save this as intents.json in the same folder as your script. Ten intents, 40 example patterns. This file is the “brain” — the code never changes, you just add to this.
{
"intents": [
{"intent": "greeting",
"patterns": ["hello", "hi", "hey", "good morning", "hi there"],
"responses": ["Hello! How can I help you today?", "Hi there! What can I do for you?"]},
{"intent": "goodbye",
"patterns": ["bye", "goodbye", "see you later", "see you"],
"responses": ["Goodbye! Have a great day.", "See you later!"]},
{"intent": "thanks",
"patterns": ["thanks", "thank you", "thanks a lot", "thank you so much"],
"responses": ["You're welcome!", "Happy to help!"]},
{"intent": "name",
"patterns": ["what is your name", "who are you", "your name"],
"responses": ["I'm TechBot, a chatbot built in Python.", "You can call me TechBot."]},
{"intent": "hours",
"patterns": ["what are your hours", "when are you open", "opening hours", "are you open"],
"responses": ["We're open Monday to Friday, 9am to 6pm."]},
{"intent": "location",
"patterns": ["where are you located", "your address", "where is your office", "location"],
"responses": ["We're located in Lahore, Pakistan."]},
{"intent": "courses",
"patterns": ["what courses do you offer", "which courses", "courses available", "do you teach python"],
"responses": ["We offer Python, Data Science and Machine Learning courses."]},
{"intent": "price",
"patterns": ["how much does it cost", "what is the price", "fees", "how much is the course"],
"responses": ["Our courses start from Rs. 5,000. Email us for details."]},
{"intent": "help",
"patterns": ["help", "i need help", "can you help me", "what can you do"],
"responses": ["I can answer questions about our courses, hours, location and prices."]},
{"intent": "weather",
"patterns": ["what is the weather", "is it raining", "weather today", "how is the weather"],
"responses": ["I can't check live weather yet, but I'm learning!"]}
]
}
Step 2 — The chatbot
Three stages: clean the text with NLTK, turn it into numbers with TF-IDF, and train a logistic regression to map numbers → intent. Then the same chat loop as before.
import json
import random
import nltk
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
# One-time downloads (NLTK 3.8.2+ uses 'punkt_tab', not 'punkt')
nltk.download("punkt_tab", quiet=True)
nltk.download("wordnet", quiet=True)
lemmatizer = WordNetLemmatizer()
def clean(text):
"""lowercase → tokenize → lemmatize → drop punctuation"""
tokens = nltk.word_tokenize(text.lower())
return " ".join(lemmatizer.lemmatize(t) for t in tokens if t.isalnum())
# 1. Load intents and build training data
with open("intents.json") as f:
intents = json.load(f)["intents"]
X, y = [], []
for it in intents:
for pattern in it["patterns"]:
X.append(clean(pattern))
y.append(it["intent"])
# 2. Text → numbers → model
vectorizer = TfidfVectorizer()
X_vec = vectorizer.fit_transform(X)
model = LogisticRegression(max_iter=1000)
model.fit(X_vec, y)
print(f"Trained on {len(X)} examples, {len(intents)} intents")
responses = {it["intent"]: it["responses"] for it in intents}
# 3. Chat loop
print("TechBot v3 ready (type 'quit' to exit)")
while True:
user = input("You: ").strip()
if not user:
continue
if user.lower() == "quit":
break
intent = model.predict(vectorizer.transform([clean(user)]))[0]
print(f"Bot [{intent}]: {random.choice(responses[intent])}")
TechBot v3 ready (type ‘quit’ to exit)
You: hi there
Bot [greeting]: Hi there! What can I do for you?
You: which courses do you offer?
Bot [courses]: We offer Python, Data Science and Machine Learning courses.
You: how much is the course
Bot [price]: Our courses start from Rs. 5,000. Email us for details.
You: where is your office
Bot [location]: We’re located in Lahore, Pakistan.
You: thank you so much
Bot [thanks]: Happy to help!
You: bye
Bot [goodbye]: See you later!
You: quit
← the [intent] is deterministic; the reply is random.choice from that intent’s list, so yours may show the other option
Look at the [intent] tags — the model classified every message correctly, including “which courses do you offer?”, which isn’t word-for-word in the training data. That’s the difference from Version 1: it generalises. The lemmatizer helped — it reduced “courses” to “course” so the question lined up with the training patterns.
What each piece does: clean() lowercases, splits into tokens, and lemmatizes (runs → run, courses → course). TfidfVectorizer turns each cleaned sentence into a vector of word weights. LogisticRegression learns which words point to which intent. At chat time the same clean → transform → predict pipeline runs on the user’s text. If you’ve done the Data Science notes, this is the same fit/predict pattern — just with text instead of numbers.
Rule-Based vs Intent-Based vs LLM API
| Rule-based (v1/v2) | Intent-based (v3) | LLM API (GPT, Claude, Ollama) | |
|---|---|---|---|
| Handles typos | v2 only | Partly (via lemmatizer) | Yes |
| New phrasings | No | Yes, if similar to examples | Yes |
| Open conversation | No | No — fixed intents only | Yes |
| Needs training data | No | Yes — you write it | No |
| Predictable answers | 100% | High | Lower — can make things up |
| Cost / internet | Free, offline | Free, offline | Paid API, or free offline with Ollama |
| Best for | Tiny FAQ, learning | FAQ bots, support, forms | General assistants, open Q&A |
Intent-based bots still run most customer-support and FAQ systems in 2026 precisely because they’re predictable: they can only say what you wrote. An LLM is the right tool when you need open conversation — and if you want that next, our AI chatbot with Flask + Ollama project builds exactly that, locally and for free.
Run It — and Add Your Own Intents
Put chatbot_v3.py and intents.json in the same folder, then:
$ python chatbot_v3.py
The first run downloads two small NLTK resources (a few MB); after that it’s instant. To teach the bot something new, you don’t touch the Python — you add an intent to the JSON:
{"intent": "refund",
"patterns": ["can i get a refund", "refund policy", "money back", "i want my money back"],
"responses": ["Full refund within 7 days of purchase — just email support."]}
Restart the script and it retrains in under a second. Rule of thumb: at least 4 patterns per intent, phrased the way real users talk (short, casual, no punctuation). The more varied your patterns, the better it generalises.
Common Mistakes (and the Exact Error You’ll See)
Mistake 1: LookupError — punkt_tab not found
LookupError:
**********************************************************************
Resource punkt_tab not found.
Please use the NLTK Downloader to obtain the resource:
>>> import nltk
>>> nltk.download('punkt_tab')
Cause: NLTK’s tokenizer data isn’t installed, or you followed an older tutorial that downloads 'punkt' — NLTK 3.8.2 and later renamed it to 'punkt_tab'.
Fix: Run nltk.download("punkt_tab") once (the script above does this automatically). If the lemmatizer complains instead, the resource is "wordnet".
Mistake 2: Empty input gives a nonsense reply (or crashes)
Cause: The user presses Enter with no text. In v3, an empty string becomes an all-zero vector and the model still “predicts” an intent — usually the same one every time, which looks like a bug. In code that does user.split()[0], it crashes with IndexError: list index out of range.
Fix: Check before predicting — that’s the if not user: continue line in v3. Always .strip() first so a line of spaces counts as empty too.
Mistake 3: KeyError: ‘intent’
KeyError: 'intent'
Cause: Your JSON uses a different key name than the code expects. Many downloaded intents.json files use "tag" instead of "intent".
Fix: Make them match — either rename the key in the JSON to "intent", or change it["intent"] to it["tag"] in both places in the script. Same applies to "patterns" and "responses".
Mistake 4: The model always predicts the same intent
Cause: Too few training examples, or one intent has many more patterns than the others, so the model learns “when unsure, say that one.” Can also mean clean() is stripping everything (check it by printing clean("hello there") — you should see hello there, not an empty string).
Fix: Give every intent at least 4 patterns and keep the counts roughly balanced. To see how confident the model is, swap predict for predict_proba and print the highest probability — if it’s below about 0.4, reply “I’m not sure” instead of guessing.
Make It Yours
The code is a template; the intents.json is the product. Some ideas that take an hour each:
- College FAQ bot — admissions, fees, timetable, exam dates, hostel. 15–20 intents.
- Shop bot — product categories, delivery times, returns, payment methods, track order.
- WhatsApp-style replies — casual tone, emojis in responses, short patterns the way people actually type.
- Personal assistant — intents that trigger Python functions: “what’s the date” →
datetime, “open youtube” →webbrowser.
Project Exercises
- Add a fallback. Use
predict_probaand reply “Sorry, I’m not sure — can you rephrase?” whenever the top probability is under 0.4. Test it with “what’s the capital of France.” - Add memory. Store the user’s name when they say “my name is X” (new intent + a bit of string parsing) and use it in later replies: “Goodbye, Ali!”
- Log the conversation. Append every
You:/Bot:pair to achat_log.txtwith a timestamp. Then read the log back and find which intent was asked most — that tells you which patterns to improve.
📥 Download: Source Code + PDF Notes
Everything on this page, ready to run:
- Source code zip —
chatbot_v1.py,chatbot_v2.py,chatbot_v3.pyandintents.json. Unzip,pip install nltk scikit-learn, run. - PDF notes — all three versions with output, the comparison table, the four mistakes and the exercises, from TechProFree. No signup required.
Final Thoughts
You built three chatbots in Python today, and more importantly you saw why each upgrade was needed: rules break on typos, fuzzy matching breaks on new phrasings, and an intent model handles both because it learns from examples instead of being told every case. That progression — rules → similarity → learned model — is the story of the whole field in miniature.
Version 3 is a real, deployable pattern. Fill the JSON with your own domain, add the confidence fallback from Exercise 1, and you have something you could put on a website or a WhatsApp number. And when you’re ready for open-ended conversation, the Flask + Ollama project takes the same loop and swaps the intent model for a local LLM.
What are you going to build — a college bot, a shop bot, something else? Hit an error that isn’t in the four above? Drop a comment, I read and reply to every one.
Frequently Asked Questions (FAQ)
An NLTK/scikit-learn chatbot classifies the user’s message into one of the intents you defined and replies with text you wrote — it’s predictable, offline, free, and can’t say anything you didn’t put in the JSON. The ChatGPT API (or a local LLM via Ollama) generates open-ended replies and can handle any topic, but it costs money per request, needs internet, and can occasionally make things up. Use intents for support/FAQ bots and an LLM for general assistants.
Yes. Version 1 and Version 2 on this page use no machine learning at all — just a dictionary of keywords and Python’s built-in difflib for typo tolerance. For a small FAQ with a handful of questions, that’s often enough. Machine learning (Version 3) becomes worth it when you need the bot to handle phrasings you didn’t explicitly anticipate.
Wrap the predict step in a small web server and call it from a chat box on the page. The simplest route is Flask: one route that receives the user’s message as JSON, runs clean → transform → predict, and returns the reply. Our Flask + Ollama chatbot project shows the complete web front-end (HTML/CSS/JS chat window) — swap its LLM call for the Version 3 predict line and it works unchanged.
For learning and for most projects, yes. Python has the best NLP and ML libraries (NLTK, spaCy, scikit-learn, Transformers), the most tutorials, and the simplest syntax, so you spend time on the chatbot rather than the language. JavaScript is the other common choice when the bot lives entirely in a web page. Start with Python; the concepts transfer.
Both are free from TechProFree via the download section above — a zip with all three .py files plus intents.json, and a PDF of these notes with every code block, output, and the common mistakes. No signup required.

