为什么这个迭代没有返回任何东西?

时间:2015-07-21 09:12:02

标签: python

def is_power(a,b):
    if a<b:
        is_power(b,a)
    elif a==b:
        return True
    else:
        if a%b !=0:
            return False
        else:
            is_power((a/b),b)


is_power(2,32)

我不知道为什么它没有显示任何内容,但是当我打印函数的最后一行“is_power((a / b),b)”时,它显示:

True
None
None
None

我在ipython笔记本中编写并运行它,而python的版本是2.7.10.1

3 个答案:

答案 0 :(得分:1)

def is_power(a,b):
    if a<b:
        return is_power(b,a)
    elif a==b:
        return True
    else:
        if a%b !=0:
            return False
        else:
            return is_power((a/b),b)

您正在运行递归函数而不返回任何步骤。

is_power(2, 32)

First step  : if a < b: return is_power(32, 2) 
Second step : (else condition): return is_power(16, 2)
Thrid step  : (else condition): return is_power(8, 2)
Fourth step : (else condition): return is_power(4, 2)
Fifth step  : (else condition): return is_power(2, 2)
Sixth step  : (elif a==b):  return True

Result: True

如果您错过任何退货声明,代码将不会返回除None

以外的任何内容

答案 1 :(得分:0)

您的程序会返回Boolean,因此您将获得TrueFalse
如果您想要不同的输出,则必须对其进行编码以生成其他内容。

代码中只有2个返回语句是:

elif a==b:
    return True

和:

else:
    if a%b !=0:
        return False



因此,您唯一可以预期的输出是TrueFalse

答案 2 :(得分:0)

您已将return语句插入相应的行,并且必须添加到代码的末尾:print is_power(x,y), 它将is_power()函数和返回值调用到输出。 仅IPython is_power(x,y)中的注释也可以。

def is_power(a,b):
    if a<b:
        return is_power(b,a)
    elif a==b:
        return True
    else:
        if a%b !=0:
            return False
        else:
            return is_power((a/b),b)


print is_power(2,32)

<强>输出:

True