为什么我的函数在 try-except 子句后返回 0?

Why is my function returning 0 after a try-except clause?

如果第一次收到有效输入,此代码将按预期工作。如果收到的输入不正确,它会提示你再试一次,当最终收到有效输入时,它会继续 return 0.

def string_num_query():
    string_num = 0
    try:
        string_num = int(input("Enter number of strings (1-6): "))
        if string_num < 1 or string_num > 6:
            print("Value must be between 1 and 6.")
            string_num_query()
    except ValueError:
        print("User input must be a number.")
        string_num_query()
    return string_num

我已经尝试按照它的流程进行操作,但看不出哪里出了问题。非常感谢任何帮助!

def string_num_query():
    string_num = 0
    try:
        string_num = int(input("Enter number of strings (1-6): "))
        if string_num < 1 or string_num > 6:
           print("Value must be between 1 and 6.")
           return string_num_query()
    except ValueError:
        print("User input must be a number.")
        return string_num_query()

   return string_num

您的递归函数不是返回递归调用的值,而是每次返回 string_num 的硬编码值。

但是,您根本不应该使用递归来实现可能的无限循环。使用 while 循环,并在 num 的值有效时跳出循环。

def string_num_query():
    while True:
        string_num = input("Enter number of strings (1-6): ")
        try:
            num = int(string_num)
        except ValueError:
            print("User input must be a number")
            continue

        if 1 <= num <= 6:
            break

    return num