Search code examples
pythonreturnshort-circuiting

python return statement in an and gate


I am not advocating this as a good style, I am just curious why it doesn't work (Invalid Syntax) and my search-fu is failing me.

def f(x):
    x and return x
    return 0

this does work in perl, e.g.:

sub f {
    my $x = shift;
    $x && return $x
    return 0
}

Solution

  • Python is a language with a distinction between statements and expressions.

    return is a statement and it cannot be used where an expression is expected.

    The opposite, as usual with languages with this duality, is instead valid because an expression can be considered a statement (so for example you can write foo() as a statement).

    If you like one liners your code can be written as

    return x if x else 0
    

    or more simply

    return x or 0
    

    because the or operator returns the first operand that is "truthy" not just True or False (and also does short-circuiting, i.e. doesn't evaluate the right operand if the left operand is truthy).