Python中函数打印和打印函数输出之间的差异

时间:2013-10-18 07:33:09

标签: python printing return

我有一个(可能是笨拙的)函数来找到数字n的最大素数因子(下图)。

def largest_prime_factor(n,factor=2):
    if n % factor == 0:
        if n == factor:
            return factor
        else:
            largest_prime_factor(n/factor,factor)
    else:
        largest_prime_factor(n,factor+1)

#Printing function output
print largest_prime_factor(600)

但是当我尝试打印函数的返回输出时,它只是说None。但是,当我让函数打印其输出(如下)时,它会输出正确的答案(5)。我在上面的片段中做错了什么?

def largest_prime_factor(n,factor=2):
    if n % factor == 0:
        if n == factor:
            print factor #Printing, not returning
        else:
            largest_prime_factor(n/factor,factor)
    else:
        largest_prime_factor(n,factor+1)

#Calling the function
largest_prime_factor(600)

1 个答案:

答案 0 :(得分:2)

你错过了一些回复电话:

def largest_prime_factor(n,factor=2):
    if n % factor == 0:
        if n == factor:
            return factor
        else:
            return largest_prime_factor(n/factor,factor)
    else:
        return largest_prime_factor(n,factor+1)