Python:为什么布尔语句打印为True但返回为None?

时间:2017-09-11 15:47:54

标签: python return boolean

我有以下代码,无法弄清楚为什么didNumExistInList()的返回值为None。 RETURN语句之前的PRINT语句打印True但返回值为None。为什么呢?

我尝试将返回值显式键入布尔值但没有帮助。

我知道这可以缩短为带印花的单线(b中的a)。这不是重点。

# Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to largest) and another number. 
# The function decides whether or not the given number is inside the list and returns (then prints) an appropriate boolean.

import math

# expecting an ordered list
def doesNumExistInList(num, listOfNum):
    # given the recursion below we're gonna end up here at some point
    if len(listOfNum) == 1:
        print (num == listOfNum[0]) # prints True
        return (num == listOfNum[0]) # returns None - why??
    elif len(listOfNum) == 2:
        print (num == listOfNum[0] or num == listOfNum[1])
        return (num == listOfNum[0] or num == listOfNum[1])

    # recursive logic
    half = math.ceil(len(listOfNum) / 2)
    if num <= listOfNum[half-1]:
        doesNumExistInList(num, listOfNum[:(half-1)])
    else:
        doesNumExistInList(num, listOfNum[half:])

a = [1,2,3,4,5,6,7,8,9]
b = 6
print (a)
print (b)
print(doesNumExistInList(b, a))

0 个答案:

没有答案