【问题标题】:Why does this iteration didn't return anything out? [duplicate]为什么这个迭代没有返回任何东西? [复制]
【发布时间】:2015-10-10 15:51:56
【问题描述】:
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 notebook 中编写并运行它,python 的版本是 2.7.10.1

【问题讨论】:

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

标签: python


【解决方案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之外的任何内容

【讨论】:

  • 这不是正确答案
  • 如下所示 is_power(2,32) 的结果为 True
  • Woups 抱歉,这是一个小错误。已更正。
【解决方案2】:

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

【讨论】:

  • 非常感谢。
  • 很高兴为您提供帮助。
【解决方案3】:

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

您的代码中仅有的 2 个返回语句是:

elif a==b:
    return True

和:

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



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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 2023-02-07
    • 2022-09-23
    • 1970-01-01
    相关资源
    最近更新 更多