【问题标题】:Return statement is not returningReturn 语句未返回
【发布时间】:2021-02-06 18:33:34
【问题描述】:

函数 PoNanswer 应该返回 True 或 False,它是一个循环,只有当你说 Yes,... 或 No,... 时才能停止,当你说它时,它应该返回。但很奇怪它没有返回......如何解决它?提前谢谢你)

def PoNanswer(voice_data):
  for i in pANSWER_LIST:
    if i in voice_data.split():
        print('true')
        return True
  for i in nANSWER_LIST:
    if i in voice_data.split():
        print('false')
        return False
  voice_data = record_audio('I did not get it. Please repeat')
  PoNanswer(voice_data)




class Command:
  def __init__(self, raw_command):
    self.raw_command = raw_command
    self.key_word = False
    self.action_word = False
    self.processing()
  def processing(self):
    print(self.raw_command)
    for i in self.raw_command.split():

        if i in COMMANDS_LIST:
            self.key_word = i
        elif i in ACTION_WORD_LIST:
            self.action_word = i


    if self.key_word == COMMANDS_LIST[0]:
        if self.action_word:
            speak('ordering...')
            main('-//-')
        else:
            if PoNanswer(record_audio(ADDITIONAL_QUESTIONS[0])):
                self.raw_command = self.raw_command + "order"
                print("mod")
                self.processing()
            else:
                speak('Okay')
                main('-//-')

            self.processing()

【问题讨论】:

  • 不知道是不是唯一的问题,但是需要返回递归调用的结果:return PoNanswer(voice_data)。最好将其包装在一个循环中,而不是使用递归。
  • @EkureEdem return 在这种情况下是正确的,break 不是。
  • @Carcigenicate 我不确定你的意思(我的知识只是实用的,不是理论上的),但它以某种方式奏效了!)谢谢
  • @NikitaAleksandrov 如果要返回值,则函数中的所有路径都必须导致返回值。当PoNanswer(voice_data)返回时,你不会对返回值做任何事情,所以函数结束,None被隐式返回。
  • 这能回答你的问题吗? Why does my recursive function return None?

标签: python-3.x return


【解决方案1】:

在这种情况下,我应该使用循环 (while 1:) 而不是在函数内部调用相同的函数。

def PoNanswer(voice_data):
while 1:
    for i in pANSWER_LIST:
        if i in voice_data.split():

            return True
    for i in nANSWER_LIST:
        if i in voice_data.split():

            return False
    voice_data = record_audio('I did not get it. Please repeat')

幸运的是,这个 ^ 有效。

def func(var):
   ...
   func(var)

这个 ^ 不是,我不知道为什么,但我很高兴它现在可以工作))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2013-03-24
    • 1970-01-01
    相关资源
    最近更新 更多