Python 2.7 While循环问题

时间:2014-09-01 03:56:42

标签: python loops python-2.7

我正在尝试为基于文本的聊天机器人编写代码作为我的第一个完整规模项目,我遇到了一个我无法弄清楚的while循环的奇怪问题。我的主循环依赖于文本输入,应该发生的是当用户键入“再见”程序结束时。唯一的问题是当我运行它时,无论我对它说什么,它只是反复打印出相同的响应,直到我按下cntrl。+ c或关闭窗口。这是代码:     导入日期时间

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

4 个答案:

答案 0 :(得分:3)

行是什么?

if user_input == "hi" or "hello":

不做你的想法。相反,你应该做

if user_input == "hi" or user_input == "hello":

甚至是以更紧凑的方式:

if user_input in ["hi","hello"]:

会发生类似的事情
elif "where" and "you" in user_input:

应该是

elif "where" in user_input and "you" in user_input:

答案 1 :(得分:0)

语法问题。

正确的形式应该是:如果A == B或A == C,而不是A == B或C,这是不正确的。

答案 2 :(得分:0)

您应该更改

if user_input == "hi" or "hello":if user_input == "hi" or user_input == "hello":

"where" and "you" in user_input:"where" in user_input and "you" in user_input:
因为"hello""where"始终是True

此外,您应将user_input=raw_input().lower().replace(" ","").replace("?","") 放入while循环。

答案 3 :(得分:0)

如果你有适当的缩进,如果循环继续运行,我认为你做了,问题,除了上面提到的关于正确使用复合if语句的事情你需要在“bye”中添加“break”情况下。

if user_input == "bye":
    print("Good bye. It was nice talking to you!")
    is_user_finished = 1
    break