Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to make a Chat Bot with Python - Part 1
ImhimLM (0)

How to make a chatbot with python

First, what is a chatbot? A chatbot is a robot you can talk to. They do specific things like playing games with you or helping you with some kind of math exam. Just name it! They are mostly made with shell languages such as bash, python, c, c++, c# and many more!

Let just get to the point. First, you would want to define 2 variables, the user input and the bot name:

userinput = input("")
botname = "Chat Bot"

Now that we have the variables, we want the bot to detect if we say "hi" in any way, it will ask you what is your name:

if ("hi" in userinput or "hey" in userinput):
     username = input("Hello! What is your name? ")
     print("You have a nice name," username)

Output:

Hello! What is your name? *type in your name*
You have a nice name, *the name you answered with*

Out of the if statement, we want to add a little game, so at the top of your script before the variable definitions, type in "import random":

import random

Now we want to make a little guessing game using if and while loops. We will also need to define a variable called "rand" for the random number:

rand = random.randint(1, 10) *This picks a number from 1 - 10*
userinput = int(input("Guess my number from 1 - 10: "))
while (userinput != rand):
     userinput = int(input("Oops! Try again! "))
     if (userinput == rand):
          print("You won! The number was", rand)

We need to make an if statement to know if you want to play the guessing game, wrap the guessing game with an if statement:

if ("guessing game" in userinput):
*The code for the guessing game goes here, don't forget your indents!*

Now we need to make the chatting go forever, to do this, wrap all of your code starting from the guessing game this is important with a "while True" loop, and after the guessing game code, type an else statement to see if the bot understands or not, and after the if-else statement, type the "userinput" input:

import random
userinput = input("")
if ("hi" in userinput or "hey" in userinput):
     username = input("Hello! What is your name? ")
     print("You have a nice name," username)
while True:
*your guessing game code goes here*
else:
     print("Sorry, I did not understand you, can you try again?")
userinput = input("")

Part 1 has finished, everyone. Goodbye until part 2! Next time, we'll add some more exciting commands!

Comments
hotnewtop
DynamicSquid (4627)

Interesting! Could you also link a repl to make it easier for someone to see the final project?