如何检查函数中执行的返回语句?

时间:2018-05-16 09:54:40

标签: python function if-statement return

您好我有一个简单的功能:

def check_val(value):
    if value < 10:
        previous = value
        return previous
    else:
        current  = value + 10
        return current

a = check_val(3)

我如何知道是否返回了currentprevious

3 个答案:

答案 0 :(得分:2)

你可以让你的函数返回一个带有必要meta的tuple并通过序列解包解压缩:

def check_val(value):
    if value < 10:
        previous = value
        return previous, 'previous'
    else:
        current  = value + 10
        return current, 'current'

a, b = check_val(3)

print(a, b)

3 previous

答案 1 :(得分:2)

除非你返回一个带有指定退出位置的标志的元组,否则你不能这样做

def check_val(val):
    if value < 10:
        previous = value
        return previous, False
    else:
        current  = value + 10
        return current, True

a, was_current = check_val(3)

print(a, was_current)  # --> 3 False

答案 2 :(得分:0)

嗯,首先,你不能直接这样做。没有办法告诉哪个返回只是从值本身发送给你的值。

你可以回复一个元组,正如其他答案中所指出的那样。

在我的观点中,如果您对这两种信息感兴趣,您应该尝试将检查与其他计算解耦,因为这样可以更容易理解返回的值。

就像那样,也许:

def check_condition(value):
    if value < 10:
        return True
    return False

def get_result(value, condition):
    if condition:
        return value
    else:        
        return value + 10

val = 5
check_result = check_condition(val)
result = get_result(val, check_result)

很难说这是否有意义,因为我不知道你的用例。在你的特定例子中,我可能会坚持元组。

相关问题