简体   繁体   English

我的代码中的递归错误-结果返回“无”

[英]recursion bug in my code - results return with “None”

The input is always passed as an string, regardless if i enter an int o str, but i'm testing if the variable is actually an integer.. if not, it raises an exception that calls the function recursively... 输入始终以字符串形式传递,无论我是否输入int ostr,但是我正在测试变量是否实际上是整数..如果不是,它将引发异常,以递归方式调用该函数...

the logic works... 逻辑有效...

but the results returns as 'None' if I start the function with an string as a variable passed to it 但是如果我使用传递给它的变量作为字符串来启动函数,则结果将返回“无”

I have tried all types of combinations... 我尝试了所有类型的组合...

The function must be executed like 'print(get_number())' 该函数必须像'print(get_number())'一样执行

I can't print the result inside the function, because it is part of the problem specification 我无法在函数内打印结果,因为它是问题说明的一部分

I have concluded that the problem is in the recursive function... but i cant figure it out 我已经得出结论,问题出在递归函数中……但我无法弄清楚

def get_number():
    val1 = input('Enter a number: ')
    try:
        val1 = int(val1)
        while val1 < 1 or val1 > 10:
            val1 = input('Enter a number: ')
            val1 = int(val1)

        str_to_print = '{:.1f}'.format(val1)
        return str_to_print

    except ValueError:
        get_number()


print(get_number())

These are the expected results: 这些是预期的结果:

and when done in that order the logic do run, but just that the resuls is 'None' 当按此顺序执行时,逻辑会运行,但结果是“无”

在此处输入图片说明

You're missing a return in the except block: 您在except块中缺少return

    except ValueError:
        return get_number()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM