【问题标题】:Recursive function in python seems to ignore nested functions if statementpython中的递归函数似乎忽略了嵌套函数if语句
【发布时间】:2021-04-30 13:52:36
【问题描述】:

我在使用递归函数时遇到了一些奇怪的行为,我无法弄清楚出了什么问题。

def setGM():

  global guild_master
  guild_master = input('>>> Enter your name: ').strip()
  
  # This statement is triggered by hitting enter to the guild_master input without typing anything, it calls setGM() again to force the user to set a name correctly.
  if guild_master == '':
      print('We need to know what to call you!')
      setGM()

  # Once the user enters a valid name, the verify function will be called to confirm the input.
  # For some reason, on the second loop/recursion it will igore the elif statement here
  def verify():
    confirm = input(f'So your name is {guild_master}, is that correct? \n>>> Please type yes or no: ').strip().lower()
    if confirm == 'no':
      setGM()
    elif confirm == 'yes':
      print(f'Yes, my name is {guild_master}')
    else:
      print('I\'m sorry, I didn\'t understand that...')
      verify()
    return

  verify()

上述代码在调用 setGM() 时提示用户输入名称。 该名称存储在 guild_master 变量中。 如果名称是非空字符串,即不是"",则调用verify() 函数来检查字符串是否为'yes'、'no' 或其他。 如果字符串为yes,则函数完成。

当初始字符串为空时会出现问题。当用户在不输入任何内容的情况下按 Enter 键进入名称提示时,就会发生这种情况。 if 语句用于检查字符串是否等于“”,如果是,则再次调用 setGM() 函数以强制用户设置有效名称。问题似乎出在这种递归上。 此时用户可能会输入一个有效的名称,然后验证功能将检查答案。 在这一点上,它预计“是”的值将像以前一样完成该功能。相反,它会再次提示用户确认。

# To simulate the correct output:
# first enter a name
# on the next prompt type yes
# console outputs "yes, my name is..."
# To simulate the incorrect output:
# when prompted to enter a name, simply hit enter without any text
# you will be prompted to enter a name again, go ahead and type something - press enter.
# console outputs "So your name is... Please type yes or no:"
# type yes
# console outputs "yes, my name is..."
# console incorrecty prompts to confirm name again
# typing 'yes' here will return the correct output and end the script.

# note, if on the first step you trigger the "Enter your name" prompt x times by hitting enter with no input, it will ask you to confirm your name x+1 times even if your answer is yes to the confirmation prompt

在这里查看它的实际效果 -> https://repl.it/@ShawnMichael2/recursivebug#main.py

【问题讨论】:

  • 为什么要为此使用递归函数?为什么不直接使用stackoverflow.com/questions/23294658/…
  • 当您在第 11 行递归运行时,它会在您的内部函数完成后从该点继续运行。只需在其后立即添加return
  • @tripleee try/catch 肯定是这里的一个选项,但对我来说,用户递归再次强制输入更简单。
  • @Axe319 太棒了,return 声明成功了。我没有意识到发生了什么,主要是由于我自己的经验不足。谢谢老哥!

标签: python python-3.x function recursion


【解决方案1】:

Axe319 在上面的评论中回答:

Python 并没有“忽略”我的 if 语句,它实际上是运行了两次。一旦进入递归,然后初始函数在我没有意识到的情况下从它停止的地方开始。第二次调用后的 return 语句停止了重复检查。

if guild_master == '':
      print('We need to know what to call you!')
      setGM()
      return

【讨论】:

    猜你喜欢
    • 2017-03-21
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    相关资源
    最近更新 更多