2017-09-12 68 views
0

我是新来的编码,并试图通过构建一个非常简单的函数来自我调整自己的递归。但是我的代码略有不同表现来我是如何期待:python递归不按预期工作

该位预期:必须不大于50

def getinput(): 
    input = int(raw_input("type number under 50 >>> ")) 
    if input < 50: 
    return input 
    else: 
    print input, "no, must be under 50" 
    getinput() 

print getinput() 

这将导致以下行为

获取用户输入的号码

C:\ Python27>蟒recur.py

类型数下50 >>> 23

这有点出乎意料

C:\ Python27>蟒recur.py

类型数下50 >>> 63

63没有,必须小于50

类型号50 >>> 23

我的问题是,为什么最后一行是“无”,而不是23?我的代码似乎正确地再次调用函数,如果用户输入数字50或更大,但为什么不第二次调用返回23(与初始输出相同)?

任何意见大加赞赏

+3

您需要'返回'函数调用,否则在这种情况下,您的原始函数将返回什么? – miradulo

回答

0

,如果数字是大于50

def getinput(): 
input = int(raw_input("type number under 50 >>> ")) 
    if input < 50: 
    return input 
    else: 
    print input, "no, must be under 50" 
    return getinput() 

print getinput() 
0

您在其他条件错过了return你不回的getInput()的结果。下面的代码应该工作:

def getinput(): 
    input = int(raw_input("type number under 50 >>> ")) 
    if input < 50: 
    return input 
    else: 
    print input, "no, must be under 50" 
    return getinput() 

print getinput() 
0

在这种情况下,你的函数将返回input

if input < 50: 
    return input 

您正在使用递归,所以它就像在结束所有返回值会回来一叠到被调用的函数。当条件if input < 50不满意时,将返回并且您正在使用print(getinput())

| 23 | 
| 63 | -> None 
----- 

这只是我对递归的理解。

因此,当值大于50时,返回的是函数返回值而不是无。

return getinput() 

也请使用而不是input不同的变量名。