Home › AI + Python: Build a Chai Chatbot › Lesson 6
A new reply every time: random.choice
AI + Python: Build a Chai Chatbot, lesson 6 of 8. simple English notes and code you can run, free.
Open the interactive lesson with Run buttonWatch on YouTube
The idea
The Part 5 bot gives the same reply every time. "menu" always gets "Masala, Adrak!". After three questions, boring!
Give each question a list of replies. Then random.choice(list) pulls one at random, like picking a slip from a box.
Add import random at the top. Press Run again and again: you get a new reply, and the same one can come back, because it is random.
- The dictionary value is now a list:
"menu": ["Masala, Adrak!", "Aaj special: Elaichi chai!", "Kadak masala try karo!"]. random.choice(replies[word])picks one item from that list.- Same question twice can give the same reply. That is normal for random.
The code
import random
replies = {"menu": ["Masala, Adrak!", "Aaj special: Elaichi chai!", "Kadak masala try karo!"],
"price": ["Rs 20", "Sirf 20 rupaye!", "Bees rupaye, bhaiya!"]}
while True:
msg = input("Aap: ").lower().strip()
for word in replies:
if word in msg:
print(random.choice(replies[word]))
Output:
Aap: menu Aaj special: Elaichi chai! Aap: menu Masala, Adrak! Aap: price Sirf 20 rupaye!
Try it yourself
- Press Run again and again. Do you always get the same replies?
- Add a fourth reply to the "menu" list.
- Add "timing": ["Subah 7 - raat 10", "Sunday bhi khula hai!"] and ask for the timing.
Remember
A list of replies plus random.choice: the bot never gets boring. Next: Part 7, the bot remembers your name.
← Understand whole sentences: the in word · Remember the name: input + variable →
All lessons: AI + Python: Build a Chai Chatbot