None 中的 Return 不是预期的

Return of None not expected

我有一个小功能如下:

# Given the numerical value of a minute hand of a clock, return the number of degrees assuming a circular clock.
# Raise a ValueError for values less than zero or greater than 59.


def exercise_20(n):
    try:
        if n < 0 or n > 59:
            raise ValueError("Number supplied is less than 0 or greater than 59")
    except ValueError as ex:
        print(ex)
    else:
        return n * 6


print(exercise_20(-15))
print(exercise_20(30))
print(exercise_20(75))

这是输出:

Number supplied is less than 0 or greater than 59
None
180
Number supplied is less than 0 or greater than 59
None

为什么我在触发异常时返回 'None'?

该函数正确打印出适当值的异常,并打印出正确范围内值的正确答案。

我不明白为什么它在触发异常时也打印 'None'。

你尝试一个块,如果它不满足你的条件 if n < 0 or n > 59,你加注。然后你抓住你的加薪并记录它。那你return什么都没有。捕获和释放是为了钓鱼:).

def exercise_20(n):
    if n < 0 or n > 59:
      raise ValueError("Number supplied is less than 0 or greater than 59")
        
    return n * 6


print(exercise_20(-15))
print(exercise_20(30))
print(exercise_20(75))

您可能也对此感兴趣:https://softwareengineering.stackexchange.com/questions/187715/validation-of-the-input-parameter-in-caller-code-duplication#。什么时候应该检查输入条件?来电者或被叫者?

你的函数应该只是引发错误。让叫来接:

def exercise_20(n):
    if n < 0 or n > 59:
        raise ValueError("Number supplied is less than 0 or greater than 59")
    return n * 6

for n in (-15, 30, 75, 30):
    print(f"{n=}:", end=" ")
    try:
        print(exercise_20(n))
    except ValueError as ex:
        print(ex)

它将输出:

n=-15: Number supplied is less than 0 or greater than 59
n=30: 180
n=75: Number supplied is less than 0 or greater than 59
n=30: 180

你编码 returns None 因为你在 print(ex) 之后没有明确的 return 语句。因此 python 隐式 returns None.

因为else:只有在没有错误的情况下才会出现。所以当出现错误时,它会跳过 else 块(也跳过其中的 return),因此返回 None。在函数定义内,打印错误,在函数定义外,打印返回的内容,导致格式为

Error (if there is one)
Return value (None (if nothing is returned) or n*6)

docs有更多信息。