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

问题描述:

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

+0

FunkySayu的答案不完全正确,看我正确的答案和下面的结果。 – Geeocode

您已将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 
+0

非常感谢。 –

+0

我很乐意帮助你。 – Geeocode

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 

如果你错过任何return语句,代码将不会返回任何东西比None

+0

这不是正确的答案 – Geeocode

+0

正如你可以看到is_power(2,32)的结果是True – Geeocode

+0

Woups抱歉,这是一个小错误。纠正。 – FunkySayu

你的程序是由返回一个Boolean,因此你要么得到一个TrueFalse
如果你想要一个不同的输出,你必须编写它来产生别的东西。

在你的代码中只有2 return语句是这些:

elif a==b: 
    return True 

和:

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



因此,你可以期望的唯一输出TrueFalse