为什么我的布尔函数有时返回 None?

dog*_*ood -1 python functional-programming if-statement function python-3.x

使用 Python 3.4。试图从 IF 语句中调用返回布尔值的函数 prime/2——总是 True 或 False。该函数运行起来很昂贵,所以我只想在我知道需要它时才调用它,因此从决策点内调用。被调用的函数不能可靠地返回 True/False。有时返回值为 None,此时测试失败。我使用 Python 的 IDLE 及其调试器。我调用 primes(2, 5, []) 并逐步执行代码。当 prime/2 到达行 elif n <= p 而 n = 5 和 p = 5 时,调试器显示 prime/2 返回 True,正如它应该的那样,但 primes/3 elif prime(m, 2) 中的行需要一个None 的值。那时我的测试失败了。我的代码:

def primes(m, n, l):        # the calling function
    if m > n:               # creates a list of primes from
        print(l, end='\n')  # m through n, inclusive
    elif m < 2:
        primes(2, n, l)
    elif m == 2:
        l.append(2)
        primes(3, n, l)
    elif m % 2 == 0:
        primes(m + 1, n, l)
    elif prime(m, 2):        # calling the second function
        l.append(m)          # to test m for primality
        primes(m + 2, n, l)
    else:
        primes(m + 2, n, l)

def prime(n, p):             # the called function will return
    if n < 2:                # True if m is prime, False otherwise
        return False
    elif n < 4:
        return True
    elif n <= p:
        return True
    elif (n > 2) and (n % p == 0):
        return False
    elif p == 2:
        prime(n, 3)
    else:
        prime(n, p + 2)
Run Code Online (Sandbox Code Playgroud)

use*_*028 5

错误在于您如何递归调用 prime()。您需要明确返回该值。像这样:

def prime(n, p):             # the called function will return
    if n < 2:                # True if m is prime, False otherwise
        return False
    elif n < 4:
        return True
    elif n <= p:
        return True
    elif (n > 2) and (n % p == 0):
        return False
    elif p == 2:
        return prime(n, 3)   # <--- RETURN VALUE
    return prime(n, p + 2)   # <--- & RETURN VALUE
Run Code Online (Sandbox Code Playgroud)