Home › AI + Python: Build a Chai Chatbot › Lesson 3
50 if-elses? Use a dictionary
AI + Python: Build a Chai Chatbot, lesson 3 of 8. A short Hinglish video, simple English notes and code you can run, free.
Open the interactive lesson with Run button
The idea
Every new question meant another elif. With 50 questions the code gets long and messy.
A dictionary is the bot's answer diary: each question (the key) points to its answer (the value).
replies.get(msg, "Samjha nahi!") looks up the answer and falls back to the default when the question is missing.
The code
replies = {"menu": "Masala, Adrak!",
"price": "Rs 20"}
while True:
msg = input("Aap: ")
if msg == "bye": break
print(replies.get(msg, "Samjha nahi!"))
Output:
Aap: menu Masala, Adrak! Aap: price Rs 20 Aap: kaise ho? Samjha nahi!
Try it yourself
- Add "timing": "Subah 7 - raat 10" to the dictionary. How many lines did it take?
- Type "Menu" with a capital M. Why does it fail? (Part 4 fixes this.)
Remember
A dictionary is the bot's diary: new question = one new line.
← Teach the bot to reply (if-else) · "MENU" or "menu"? .lower() + .strip() →
All lessons: AI + Python: Build a Chai Chatbot