Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Conditions: Write Clear Conditional Logic

Understand Python's boolean operators and truthiness rules, then apply them to write readable conditions with practical examples.

~4 min readPython
#Python#Conditional Statements#Boolean Logic#Truthiness
Illustration of a Python code snippet with branching condition paths represented by a logic gate and decision points.

A condition in Python is any expression that can be evaluated as True or False. Conditions appear in if statements, while loops, list comprehensions, and filter() calls. The and, or, and not operators combine or invert conditions, and their behavior depends on Python's truthiness rules. Understanding those rules prevents subtle bugs and makes your code more readable.

Boolean Operators: and, or, not

Python provides three boolean operators: and, or, and not. The and and or operators work with truthy and falsy values and return one of their operands, not necessarily a boolean. The not operator always returns a boolean. This distinction is a common source of confusion.

The and operator evaluates the left operand first. If it is falsy, it returns that operand without evaluating the right side. If the left operand is truthy, it evaluates the right operand and returns it. The or operator does the opposite: if the left operand is truthy, it returns it; otherwise, it evaluates and returns the right operand. The not operator always returns a boolean: True if the operand is falsy, False if truthy.

python
# and returns the first falsy value or the last value print(0 and 5) # 0 print(1 and 5) # 5 print(1 and 0) # 0 # or returns the first truthy value or the last value print(0 or 5) # 5 print(1 or 5) # 1 print(0 or 0) # 0 # not always returns a boolean print(not 0) # True print(not 5) # False

This behavior is useful for default values, but it can lead to unexpected results if you assume and and or always return True or False. For example, a and b returns b when a is truthy, which might not be what you expect in a boolean context. Use explicit comparisons when you need a strict boolean.

Truthiness: What Python Treats as False

Python's bool() function converts any object to a boolean based on its truthiness. The following values are considered falsy:

  • None
  • False
  • zero of any numeric type: 0, 0.0, 0j
  • empty sequences and collections: '', [], (), {}, set(), range(0)

Everything else is truthy, including non-empty strings, lists, and custom objects (by default). This truthiness model lets you write concise conditions like if items: to check for a non-empty list, or if user: to check that a user object is not None.

python
def process_items(items): if items: # items is not empty for item in items: print(item) else: print('No items to process')

However, relying on truthiness can be dangerous when you need to distinguish between None, zero, or an empty container. For example, if score: will skip score = 0, which might be a valid value. In such cases, use an explicit comparison like if score is not None:.

Conditional Expressions: The Ternary Operator

Python's conditional expression, often called the ternary operator, provides a compact way to choose between two values based on a condition. The syntax is value_if_true if condition else value_if_false. It evaluates the condition and returns the appropriate branch.

python
status = 'active' if user.is_active else 'inactive'

This is equivalent to an if-else statement but is more concise when you need to assign a value. Use it sparingly; for complex conditions, a regular if statement is often clearer.

Conditional expressions can be nested, but nesting hurts readability. For example:

python
result = 'high' if score >= 90 else ('medium' if score >= 50 else 'low')

While this works, it's harder to read than a multi-branch if statement. Prefer clarity over brevity when the logic isn't trivial.

Common Pitfalls with Conditions

Several mistakes frequently trip up developers when writing conditions in Python.

Using & Instead of and

The & operator is bitwise AND, not logical AND. When applied to booleans, & behaves like and, but it does not short-circuit and it has a different precedence. Mixing them can cause subtle errors, especially with integers.

python
# Logical AND if a and b: pass # Bitwise AND (not for conditions) if a & b: # works for booleans but not for truthiness pass

For conditions, always use and and or. Reserve & for bitwise operations on integers.

Chaining Comparisons Incorrectly

Python supports chained comparisons like a < b < c, which is equivalent to a < b and b < c. This is a convenient feature, but it can be confusing when combined with and or or.

python
# Correct chaining if 0 < x < 10: pass # Avoid mixing with and if 0 < x and x < 10: pass # works but redundant

Chaining is evaluated only once for the middle operand, which matters if the expression has side effects.

Assuming and and or Return Booleans

As shown earlier, and and or return operands, not necessarily True or False. If you need a boolean result, wrap the expression with bool() or use explicit comparisons.

python
value = a and b # might be non-boolean if value: # works but hides the type pass # Better if you need a boolean is_valid = bool(a and b)

Short-Circuit Evaluation and Performance

Both and and or short-circuit: they stop evaluating as soon as the result is determined. This has performance and correctness implications.

For and, if the left operand is falsy, the right operand is never evaluated. For or, if the left operand is truthy, the right operand is skipped. This can save expensive function calls or avoid errors.

python
def get_user(): # expensive database call return user # If user is None, get_user() is not called if user is not None and get_user().is_admin: pass

In the example above, if user is None, the and short-circuits and get_user() is never called, preventing a potential AttributeError. This is a common pattern for guarding against None.

Short-circuiting also affects performance when the right operand is computationally heavy. Place cheaper checks first to avoid unnecessary work. However, do not reorder conditions if the right operand has side effects that must occur only under certain conditions—the order defines the semantics.

Writing Readable Conditions

Conditions are part of the code's interface. Readable conditions reduce bugs and make maintenance easier. Here are practical guidelines:

  • Use descriptive variable names in conditions, such as is_authenticated instead of user.status == 1.
  • Prefer positive conditions when possible. if not is_disabled is less clear than if is_enabled.
  • Extract complex conditions into named functions or variables.
python
# Instead of a long condition if user.is_active and user.has_permission('edit') and not user.is_banned: pass # Extract into a function def can_edit(user): return user.is_active and user.has_permission('edit') and not user.is_banned if can_edit(user): pass

This improves readability and makes the condition testable in isolation.

Another technique is to use the all() or any() functions for iterable conditions. They are more declarative and avoid repetitive and/or chains.

python
checks = [ user.is_active, user.has_permission('edit'), not user.is_banned, ] if all(checks): pass

all() short-circuits on the first falsy value in the iterable, and any() short-circuits on the first truthy value. If you need that short-circuit to avoid evaluating later checks, pass a generator expression instead of a pre-built list; otherwise, the checks are evaluated before all() or any() is called.

When writing conditions, always consider how they will read six months later. A condition that is easy to parse at a glance is worth a few extra lines of code.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.