You can build a chatbot in Python using a response function, a conversational state dictionary and a simple input loop. This guide includes complete original chatbot code and six locally verified tests. The example is a fictional library assistant that handles opening-hours questions, remembers a topic and falls back when a request is unsupported.
What does chatbot code need to do?
A chatbot receives a message, identifies an appropriate response, and returns it to the user. Some bots follow fixed rules, others retrieve answers from a collection of documents, and generative bots call a language model. This tutorial builds the first type to teach chatbot programming without network access or API fees.
A useful beginner project separates the response function from the interface. That makes the core behavior testable without simulating every keyboard input. For the broader architecture of a generative assistant, see our generative AI chatbot development guide.
Set up the Python project
Install Python 3 and create a local folder containing chatbot.py and test_chatbot.py. The example uses only the standard library. There is no model download or credential requirement. All opening hours and library policies in this example belong to a fictional library.
The bot supports two topics: opening hours and library cards. It remembers the active topic in a dictionary for the current session, so a follow-up question about weekends can use the previous message.
Complete Python chatbot code
import re
def respond(message, state):
words = set(re.findall(r'[a-z]+', message.lower()))
if not words:
return 'Please enter a question.'
if 'reset' in words:
state.pop('topic', None)
return 'Conversation reset.'
if 'hours' in words:
state['topic'] = 'hours'
return 'The demo library opens from 9 am to 5 pm on weekdays.'
if 'weekend' in words and state.get('topic') == 'hours':
return 'The demo library is closed on weekends.'
if 'card' in words:
state['topic'] = 'card'
return 'Ask the demo library desk about a library card.'
return 'I can help with hours or library cards.'
if __name__ == '__main__':
state = {}
while True:
try:
message = input('You: ')
except (EOFError, KeyboardInterrupt):
break
if message.strip().lower() == 'quit':
break
print('Bot:', respond(message, state))
Save the code as chatbot.py and run python chatbot.py. The response function tokenizes lowercase English input into whole alphabetic words. This avoids the substring problem where a word such as cardboard might be mistaken for card. It is still a limited rule system, not a general natural-language understanding model.
The order of the checks matters. Reset clears the topic, opening-hours questions establish context, and weekend questions use that context. The loop ends when the user types quit or closes the input stream.
Try a sample conversation
You: HOURS?
Bot: The demo library opens from 9 am to 5 pm on weekdays.
You: weekend?
Bot: The demo library is closed on weekends.
You: reset
Bot: Conversation reset.
You: weekend?
Bot: I can help with hours or library cards.
This transcript illustrates the expected behavior of the tested response function. The bot does not retain messages between processes or access real library information. It also does not infer complicated requests, distinguish all negations or handle multiple intents reliably. Keep the fallback explicit instead of inventing answers.
Add six unit tests
Save the following as test_chatbot.py in the same folder. The Python standard-library unittest module lets you isolate each case and compare actual responses with expected behavior.
import unittest
from chatbot import respond
class BotTests(unittest.TestCase):
def test_hours(self):
self.assertIn('9 am', respond('HOURS?', {}))
def test_followup(self):
state = {}
respond('hours', state)
self.assertIn('closed', respond('weekend?', state))
def test_reset(self):
state = {'topic': 'hours'}
respond('reset', state)
self.assertEqual(state, {})
self.assertIn('I can help', respond('weekend?', state))
def test_empty(self):
self.assertEqual(respond(' ', {}), 'Please enter a question.')
def test_word_boundary(self):
self.assertIn('I can help', respond('cardboard', {}))
def test_isolation(self):
respond('hours', {})
self.assertIn('I can help', respond('weekend?', {}))
if __name__ == '__main__':
unittest.main()
python -m unittest -v
All six tests of the original response function passed in our local Python test on December 4, 2026. They cover normalization, follow-up context, resetting state, blank input, whole-word matching and session isolation. The interactive terminal loop was not separately exercised. These are deterministic functional checks, not evidence that the bot understands all possible questions.
Add new tests whenever you add a rule, especially when two topics overlap. For more original exercises, see our Python AI code examples.
Extend the bot to retrieval or a language model
When your fixed rules cannot cover realistic phrasing, a retrieval system can select relevant approved passages before constructing an answer. A language model can help with flexible wording, but its output requires separate validation and controls.
Keep the response function independent of the terminal interface. You can later call it from a web endpoint or replace its rule-selection stage with a provider adapter. Our chatbot API example demonstrates a separate Python HTTP endpoint with request validation. Do not expose model API credentials in client-side code.
For production, allocate session state per authenticated user, restrict the knowledge that users can retrieve, limit input size, define fallback behavior and test representative conversations. Do not reuse the demo’s in-memory dictionary as a shared production store.
Code-based and no-code chatbot programming options
Plain Python is a good way to learn the mechanics. A chatbot library can offer response selection and training features, while hosted LLM APIs expose generative capabilities. No-code chatbot platforms provide visual workflows and can reduce the amount of application code required. Select based on the control and maintenance your project needs.
During our review, we consulted Voiceflow’s July 2026 Python chatbot tutorial, Real Python’s May 2026 ChatterBot guide, and official Python unittest documentation. The first two cover multiple implementation approaches; the original example here instead emphasizes explicit state and reproducible tests without additional dependencies. iTechGuides and SchoolWhool search extracts provided further context, but their full pages were inaccessible. No third-party framework was installed or evaluated.
Frequently asked questions
Is this chatbot an AI model? No. It is a deterministic rule-based program.
Can I build a chatbot without an API key? Yes. This local example uses only Python’s standard library.
Can this bot remember conversations? It remembers one active topic during a session. It does not retain the full transcript or persist memory between runs.
Is this ready for a website? Not by itself. A website integration requires a server interface, session isolation, appropriate security and testing.
How can I use an AI model instead? Replace the response-selection layer with an authorized model or retrieval integration and test the new behavior independently.

