I am trying to write a code for a text based chat-bot as my first full scale project and I am having a weird problem with while loops that I can't figure out. My primary loop is dependent on text input, what is supposed to happen is when the user types "bye" the program ends. The only problem is when I run it, no matter what I say to it, it just prints out the same response over and over until I hit cntrl.+c or close the window. Here is the code: import datetime
print("Hi I am ChatBot V 0.0.1. I am here to converse. ")
user_name=raw_input("What is your name?")
print("Hello " + user_name + "!")
user_input=raw_input().lower().replace(" ","").replace("?","")
is_user_finished=0
while (is_user_finished == 0):
if user_input == "hi" or "hello":
print("Hello. How are you?")
elif user_input == "whatisyourname":
print("I do not have a name at the moment. What do you think I should be named?")
user_input=raw_input().lower().replace(" ","").replace("?","")
print("Good choice! I like that name!")
elif "where" and "you" in user_input:
print("I was typed up by some kid in California")
else:
print("I do not currently understand what you said. Sorry.")
if user_input == "bye":
print("Good bye. It was nice talking to you!")
is_user_finished = 1
What happens is that the line
if user_input == "hi" or "hello":
don't do what you think. Instead, you should do
if user_input == "hi" or user_input == "hello":
or even, in a more compact way:
if user_input in ["hi","hello"]:
Something similar happens with the line
elif "where" and "you" in user_input:
which should be
elif "where" in user_input and "you" in user_input:
syntax issue.
the correct form should be : if A == B or A == C, instead of A == B or C, which is incorrect.
You should change the line
if user_input == "hi" or "hello":
to if user_input == "hi" or user_input == "hello":
and
"where" and "you" in user_input:
to "where" in user_input and "you" in user_input:
,
because "hello"
and "where"
is always True
.
Besides you should put user_input=raw_input().lower().replace(" ","").replace("?","")
into the while loop.
Provided you have proper indentation, which if the loop keeps running I assume you do, the problem, besides the things pointed out above about proper use of compound if statements is you need to add a "break" to the "bye" case.
if user_input == "bye":
print("Good bye. It was nice talking to you!")
is_user_finished = 1
break
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.