Python Boolean Operators: Usage of and, or, not and Short-Circuit Evaluation

When handling conditional branches like if statements in Python, you often want to combine multiple conditions. For example, “User is authenticated AND is an administrator” or “Process failed OR timed out.”

To achieve this, Python provides Boolean Operators (Logical Operators): and, or, and not.

This article explains how to use these three operators and the important concept of “Short-Circuit Evaluation.”


目次

not Operator (Logical Negation)

The not operator reverses a boolean value.

  • not True becomes False.
  • not False becomes True.

It is used to specify a “is NOT” condition.

is_active_user = False

# Evaluates to True because is_active_user is False
if not is_active_user:
    print("User is not active.")

# ---
is_connected = True

# Since is_connected is True, adding 'not' makes it False
if not is_connected:
    print("Not connected.") # This line is not executed

Output:

User is not active.

and Operator (Logical AND)

The and operator evaluates to True only if both conditions are True. If even one is False, the result is False.

This corresponds to the condition “A AND B”.

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
# Permission check example
is_authenticated = True # Logged in
is_admin = False        # Not an admin

# Must be authenticated AND be an admin
if is_authenticated and is_admin:
    print("Access allowed to Admin Menu.")
else:
    print("Access denied. ('and' condition is False)")

Output:

Access denied. ('and' condition is False)

or Operator (Logical OR)

The or operator evaluates to True if at least one of the conditions is True. It evaluates to False only if both are False.

This corresponds to the condition “A OR B”.

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
# Error check example
has_network_error = False
has_timeout = True

# If network error OR timeout occurred
if has_network_error or has_timeout:
    print("Process failed. ('or' condition is True)")
else:
    print("Process completed successfully.")

Output:

Process failed. ('or' condition is True)

Important Concept: Short-Circuit Evaluation

The and and or operators perform a very important behavior called “Short-Circuit Evaluation.”

This means that Python stops evaluating the expression as soon as the result is determined.

1. Short-Circuiting with and

In A and B: If A is False, the entire result is guaranteed to be False (regardless of B).

Therefore, Python does not evaluate B if A is False.

2. Short-Circuiting with or

In A or B: If A is True, the entire result is guaranteed to be True (regardless of B).

Therefore, Python does not evaluate B if A is True.

Benefits of Short-Circuit Evaluation

This mechanism helps improve efficiency and avoid errors.

Example: Avoiding Errors

It is often used to check if an object is not None before calling a method on it.

user_object = None # Assume the user object does not exist yet

# If there were no short-circuit evaluation, Python would try to run
# 'user_object.is_active()' and crash with:
# 'NoneType' object has no attribute 'is_active'
#
# Thanks to 'and' short-circuiting:
# 1. 'user_object is not None' evaluates to False.
# 2. The right side 'user_object.is_active()' is SKIPPED.
# 3. The if statement becomes False safely, avoiding the crash.
if user_object is not None and user_object.is_active():
    print(f"{user_object.name} is active.")
else:
    print("User does not exist or is not active.")

Output:

User does not exist or is not active.

Summary

  • not: Reverses the boolean value (“Not A”).
  • and: Returns True only if both are True (“A and B”).
  • or: Returns True if at least one is True (“A or B”).
  • Short-Circuit Evaluation:
    • and: If the left side is False, the right side is ignored.
    • or: If the left side is True, the right side is ignored.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次