TypeError:只能将 str(不是“NoneType”)连接到 strTypeError:只能将 str(不是“NoneType”)连接到 python 聊天机器人中的 str

问题描述 投票:0回答:1

我正在尝试仅使用python做一个聊天机器人,但是我对调用机器人响应的主函数有问题,调用它时发生异常。

这是机器人响应的主要功能

while True :
   print('Bot:' + get_response(input('You: ')))

我期待机器人给出适当的回应,但我得到了这个:

File "C:\Users\ivann\PycharmProjects\pythonProject\main.py", line 51, in <module>
    print('Bot:' + get_response(input('You: ')))
          ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TypeError: can only concatenate str (not "NoneType") to str
python project chatbot
1个回答
0
投票

使用 Python(和其他一些语言)编码时,通常最好避免连接字符串。这是一个例子:

x = 12

# bad
print("x has value " + str(x))

# very bad; raises an exception unless x is a string
print("x has value " + x)

# good
print("x has value", x)

# also good
print(f"x has value {x}")

您遇到了错误,因为

get_response()
返回了值
None
,而 Python 不知道如何使用
None
运算符将
+
与字符串组合。

© www.soinside.com 2019 - 2024. All rights reserved.