Search⌘ K

Conditions Related Tips

Explore key tips for writing safe and effective conditions in Python. Understand operator precedence, use assert statements for debugging, check values with membership operators, and avoid common pitfalls with boolean and bitwise operators to produce reliable and maintainable code.

Compare one to many

We have a variable and we want to check if its value is permissible. Let’s say that the user enters the name of a day and we want to check if it’s Saturday or Sunday. It seems obvious in Python, but it’s not:

if day.lower() == 'saturday' or 'sunday': # It’s weekend!

The boolean or operator has lower precedence than the comparison operator (==), which means that the comparison is evaluated before the boolean operator. So if we place parentheses around the higher-precedence operator to avoid confusion, the above statement looks like this:

if (day.lower() == 'saturday') or 'sunday': ...

The value of an or expression is true if any of its operands are true. The non-empty 'sunday' string is always interpreted as true. Thus, the condition is always true, regardless of the day. It’s good to have a never-ending weekend.

Perhaps, then, we should adjust the precedence by enclosing the or expression in the parentheses?

if day.lower() == ('saturday' or 'sunday'): ...

No, again. The value of the or operator is first True operand, or False if both operands are false. Because 'saturday' is a non-empty string, it’s interpreted as true. The expression in the parentheses is always 'saturday' and never 'sunday'. The expression treats Sunday as a weekday. We’d rather have a never-ending weekend than a one-day weekend.

The correct way to go is to check if the day is in a collection of suitable days using the membership operator, in. The collection can be a list, a tuple, or even a dictionary, but we get optimal performance by using sets.

if day.lower() in
...