尝试创建递归函数以从用户那里获得 y/n 答案,但是当它重复出现时,检查将停止工作

Trying to make a recursive function to get a y/n answer from the user, but when it recurs the check stops working

预期的输出是它会重复出现,直到用户给出是或否的答案,如果他们给出是,则执行代码,在这种情况下只打印 "yep"。如果用户立即输入 "Y",一切正常,但当输入非法并且程序要求另一个输入时,用户输入检查停止工作。

示例:

(Y/N) y
yep

结束


(Y/N) illegal

出了点问题,请确保输入正确,然后重试!

(Y/N) y

结束

我做错了什么?

def user_choice():
    answer = input("(Y/N) ")
    if answer.lower() == "n": return False
    elif answer.lower() == "y": return True
    else:
        print("Something went wrong, make sure you made the right input and try again!")
        user_choice()

if user_choice(): print("yep")

不要以递归方式执行此操作。那简直就是错误的选择。您当前问题的解决方案是您需要 return user_choice() 而不仅仅是 user_choice(),但迭代解决方案要聪明得多:

def user_choice():
    while True:
        answer = input("(Y/N) ")
        if answer.lower() == "n":
            return False
        elif answer.lower() == "y":
            return True
        else:
            print("Something went wrong, make sure you made the right input and try again!")

if user_choice():
    print("yep")

你没有return递归的结果。你可以使用这样的东西。

def user_choice():
    answer = input("(Y/N) ")
    if answer.lower() == "n": return False
    elif answer.lower() == "y": return True
    else:
        print("Something went wrong, make sure you made the right input and try again!")
        user_choice()

if user_choice(): print("yep")

两件事:

  1. 您的代码中缺少带有函数签名的一行。我假设它应该看起来像这样:
def user_choice():
  1. 当代码采用 else 路径时,您不会返回任何内容,因此当初始选择非法时(实际上返回 None),不会返回任何内容。所以像这样更新你的函数:
    answer = input("(Y/N) ")
    if answer.lower() == "n": return False
    elif answer.lower() == "y": return True
    else:
        print("Something went wrong, make sure you made the right input and try again!")
        return user_choice()  # <-- need to return a meaningful value here
  1. 递归是解决此类问题的糟糕选择。循环更易于编写、更易于阅读且性能更好:
def user_choice():
    while True:
        answer = input("(Y/N) ")
        if answer.lower() == "n": return False
        elif answer.lower() == "y": return True
        print("Something went wrong, make sure you made the right input and try again!")