相关疑难解决方法(0)

为什么我的递归python函数返回None?

我有这段自称的代码:

def get_input():
    my_var = input('Enter "a" or "b": ')

    if my_var != "a" and my_var != "b":
        print('You didn\'t type "a" or "b". Try again.')
        get_input()
    else:
        return my_var

print('got input:', get_input())
Run Code Online (Sandbox Code Playgroud)

现在,如果我输入"a"或"b",一切都很好.输出是:

Type "a" or "b": a
got input: a
Run Code Online (Sandbox Code Playgroud)

但是,如果我输入其他内容然后输入"a"或"b",我会得到:

Type "a" or "b": purple
You didn't type "a" or "b". Try again.
Type "a" or "b": a
got input: None
Run Code Online (Sandbox Code Playgroud)

我不知道为什么get_input()要回来None,因为它应该只返回my_var.print语句显示None正确的值,但函数由于某种原因不返回该值.

python recursion return function

46
推荐指数
2
解决办法
7万
查看次数

返回递归函数

我刚刚开始学习python(v3.2.3)并且return在这个函数中遇到了一个奇怪的问题:

def test(x):
    if x > 9 :
        test(x - 10)
    else:
        print('real value',x)
        return x

x = int(input())
y = test(x)
print('this should be real value',y)
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到:

45
real value 5
this should be real value None
Run Code Online (Sandbox Code Playgroud)

但我预计:

45
real value 5
this should be real value 5
Run Code Online (Sandbox Code Playgroud)

我尝试return x在外面添加if,我得到了默认输入值.任何人都可以解释一下return有效吗?

python recursion return

38
推荐指数
3
解决办法
2万
查看次数

标签 统计

python ×2

recursion ×2

return ×2

function ×1