错误,文件“<ipythoninput453a28643f7b0c>”,第12行随机返回。选择(机器人问候语)^SyntaxError:函数外的“返回”

2024-05-15 16:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,返回语句中出现语法错误

#function to return a random greeting to user's greeting
def greeting_response(text):
 text = text.lower()

#Bots Greeting Response
bot_greeting = ['hi', 'hello', 'how can i help you', 'welcome']
#users greetings
user_greeting = ['hi', 'hello','hey']

for word in text.split():
    if word in user_greeting:
     return random.choice(bot_greeting)

运行时遇到的错误是:

文件“”,第12行 返回random.choice(bots\u问候语) ^ SyntaxError:函数外部的“return”

有人能帮我找出我犯了什么错误吗? 当我尝试打印而不是返回时,它工作正常,但返回时会出现错误


Tags: to代码textinhelloreturnbot错误
1条回答
网友
1楼 · 发布于 2024-05-15 16:35:12

基本上,这是由于无效缩进造成的。下面的代码应该可以工作:

import random


#function to return a random greeting to user's greeting
def greeting_response(text):
    text = text.lower()

    #Bots Greeting Response
    bot_greeting = ['hi', 'hello', 'how can i help you', 'welcome']
    #users greetings
    user_greeting = ['hi', 'hello', 'hey']

    for word in text.split():
        if word in user_greeting:
            return random.choice(bot_greeting)


print(greeting_response('hi'))

我强烈建议您使用任何代码编辑器,如PyCharmVS

相关问题 更多 >