And + or

In Python, and and or work in a slightly unusual way, which means they can be used to assign values.

Rather than write:

if n < 0:
    result = 'n is negative'
    result = 'n is positive'

You can write:

result = n < 0 and 'n is negative' or 'n is positive'

The result is shorter, though I'm not sure it's more readable. However, the fact that it's a single line makes it more versatile. For example, you can include it in a list comprehension, as I did in this contrived example, or you can pass it as an argument to a function.

Then general form is:

result = test and true_result or false_result

The logic is that the two results count as being true, so if the test is true, then test and true_result is true; if the test is false then test or false_result is true.

There is a more detailed explanation of why this trick works at Dive Into Python.


I like the more pythonic way, too:

result = true_result if test else false_result;

Nice, I don't think I've ever seen that pattern before.

The positive and negative are switched in the second line 1 above.

Good point. I've fixed it.

Post new comment

The content of this field is kept private and will not be shown publicly.