You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用函数验证用户输入并在另一函数中使用?代码报错求解

问题解决:输入验证后跨函数调用&代码报错修复

问题根源

你的代码里user_input()函数有个致命问题:当输入的option不在1-3范围内时,你递归调用了user_input()但没有返回递归的结果。这导致第一次输入错误、第二次输入正确时,外层的user_input()会返回None,而不是正确的option值。main()函数拿到None后,自然会走到else分支打印“Invalid option”。

另外,原输入验证逻辑的三个if是独立判断,会重复触发提示,且没有循环让用户重新输入,只能靠递归,逻辑不够清晰。

修复后的代码

方案1:修复递归的return语句

只需要在递归调用时加上return,让正确的值能逐层返回:

def user_input():
    while True:
        try:
            option = int(input("Enter an option: "))
            break
        except ValueError:
            print("Invalid input. Please enter a number between 1 and 3.")
    
    if option < 1:
        print("Invalid value. Please enter an integer between 1 and 3.")
        return user_input()  # 加上return传递递归结果
    if option > 3:
        print("Please enter an integer between 1 and 3.")
        return user_input()  # 加上return传递递归结果
    if 1 <= option <= 3:
        return option


def main():
    option = user_input()
    if option == 1:
        print("Option 1 Selected")
    elif option == 2:
        print("Option 2 Selected")
    elif option == 3:
        print("Option 3 Selected")
    else:
        print("Invalid option")


if __name__ == "__main__":
    main()

方案2:用while循环替代递归(更推荐)

递归在这里没必要,用单层while循环能让逻辑更清晰,还能避免栈溢出风险:

def user_input():
    while True:
        try:
            option = int(input("Enter an option: "))
            if 1 <= option <= 3:
                return option
            else:
                print("Please enter an integer between 1 and 3.")
        except ValueError:
            print("Invalid input. Please enter a number between 1 and 3.")


def main():
    option = user_input()
    if option == 1:
        print("Option 1 Selected")
    elif option == 2:
        print("Option 2 Selected")
    elif option == 3:
        print("Option 3 Selected")


if __name__ == "__main__":
    main()

关于“验证后输入跨函数调用”的实现

核心逻辑很简单:

  • 让负责输入验证的函数(比如user_input())返回合法的输入值
  • 在需要使用该输入的函数(比如main())里,调用这个验证函数并接收它的返回值,之后直接用这个变量即可。

就像上面的代码里,main()通过option = user_input()拿到验证后的合法值,后续直接判断使用就行。

内容的提问来源于stack exchange,提问作者Voook

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:33:51