About Logical Operators in Python

In Python, or conditions return the first true-ish component and ignore the execution of others.

The and conditions return the last true-ish component if all components are true-ish or the first falsy component otherwise.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def get(x):
    print(x)
    return x

result = get(1) or get(2) or get(3)
# Will print 1 and return 1.
# 2 and 3 will be ignored.

result = get(1) and get(2) and get(3)
# Will print 1, 2, 3 and return 3.

This can be used in some cases to avoid if conditions and have shorter code, e.g.:

1
2
3
4
5
title = instance.title_de or instance.title_en
# if German title doesn't exist, get the English one

user = post and post.author 
# if post is not None, get its author

Tips and Tricks Programming Python 3