Skip to content

Boolean logic in Python: and, or, not, precedence and common mistakes

Python spells the three basic operators as words, and, or and not, ranks them in that order below the comparison operators, and returns an operand rather than a plain Boolean from and and or. The listing below is the engine's own Python export of the entry rule.

LogicPythonNote
NOT Anot aLower precedence than comparisons: not a == b is not (a == b)
A AND Ba and bShort-circuits; returns an operand
A OR Ba or bShort-circuits; returns an operand
A XOR Ba != b or a ^ b on bools^ is bitwise on integers
A -> B(not a) or bNo implication operator
A <-> Ba == b on boolsEquality of two Booleans
TRUE, FALSETrue, FalseCapitalised; 1 and 0 are integers, not accepted by the export

The words are the operators: a and b, a or b, not a. Precedence is not, then and, then or, the same order as this reference, with one twist that catches people: comparisons bind tighter than not, so not a == b is not (a == b). The pitfall page on precedence across languages shows the slip; the parser here rejects that spelling outright rather than guessing.

and and or short-circuit and return one of their operands, not necessarily True or False: 0 or 5 is 5 and '' and 'x' is ''. That is convenient and a trap, because a value that is merely truthy (a non-empty list, a non-zero number) is not the Boolean True. The exported module refuses such values: its input contract requires every input to be exactly True or False, and anything else, including 0, 1 and None, raises an InputError before evaluation.

The single-character operators belong to integers: &, |, ^ and ~ are bitwise. On two bool values &, | and ^ happen to give Booleans (True ^ False is True), but ~True is -2, and != between Booleans is exclusive or. The export is generated deterministically from the validated model, one function per output (output_allow_entry(inputs)) plus an in_scope check for the declared assumptions, and its header says what it does not establish: that the rule is complete, legal or safe.

Reading the export

The module header records the engine and semantics versions and two digests, one of the logic and one of the assumptions, so a reviewer can tell which revision of the rule produced the file. Inputs are passed as a dict keyed by their declared names; outputs are functions of that dict. Nothing in the file reads the network, the file system or the clock.

The entry rule, as the engine exports it

allow_entry := (member OR invited) AND NOT banned
# -*- coding: utf-8 -*-
# Generated by Tangibool (tangibool.python/1). Do not edit by hand; regenerate from the source revision.
# Model: not stated
# Source revision: reference
# Interpretation status: not stated
"""Tangibool evaluator (decision model).

Generated deterministically from the validated Boolean model; it evaluates exactly that
model. It does not establish that the model is a complete, legal, or safe statement of a
real-world rule, and evaluating examples does not verify the rule.

Source revision: reference
Interpretation status: not stated
Exporter: 1.0.0 (format tangibool.python/1; engine 1.0.0; semantics tangibool-semantics/1)
Logic digest: f0daa82174670c788f59eb058d07f7601cd0ace4ed94d61a747cc26c41fd4e0d
Assumptions digest: d58ee1ad38e23e5093e4baa1047b5ae70d6972e08f555e34ac3fa16df63c4a78

Inputs (dict keys, declared order) and generated parameter names:
    'member' -> input_member
    'invited' -> input_invited
    'banned' -> input_banned

Outputs (declared order) and their functions:
    'allow_entry' -> output_allow_entry(inputs)

Assumptions (the declared scope, checked by in_scope(inputs)):
    none; every complete assignment is in scope.

Input contract:
    Every required input must be exactly True or False (type(value) is bool). Missing
    inputs, None, strings, integers (including 0 and 1), and keys that are not declared
    inputs raise InputError before anything is evaluated, including inputs that a
    short-circuiting operator would never read. Results are always bool.

Scope:
    Decision functions raise OutOfScopeError when the inputs violate an assumption; an
    out-of-scope assignment is never turned into a False result. Pass check_scope=False
    to evaluate without the scope check, and use in_scope(inputs) to test it separately.

Usage:

    import tangibool_model as model

    model.evaluate({'member': False, 'invited': False, 'banned': False})
    # -> {'allow_entry': False}
    model.output_allow_entry({'member': False, 'invited': False, 'banned': False})
    # -> False
    model.evaluate({'member': 1, 'invited': False, 'banned': False})
    # raises InputError: 1 is an int, not a bool
"""

import collections.abc as _abc
from typing import Dict, Mapping, Tuple

__all__ = [
    "MODEL_INFO",
    "IDENTIFIER_MAP",
    "INPUT_NAMES",
    "OUTPUT_NAMES",
    "ASSUMPTIONS",
    "InputError",
    "OutOfScopeError",
    "minterm_index",
    "in_scope",
    "evaluate",
    "output_allow_entry",
]

MODEL_INFO = {
    "format": "tangibool.python/1",
    "mode": "decision",
    "model": None,
    "revision": "reference",
    "interpretation": None,
    "exporter": "1.0.0",
    "engine_version": "1.0.0",
    "semantics_version": "tangibool-semantics/1",
    "logic_digest": "f0daa82174670c788f59eb058d07f7601cd0ace4ed94d61a747cc26c41fd4e0d",
    "assumptions_digest": "d58ee1ad38e23e5093e4baa1047b5ae70d6972e08f555e34ac3fa16df63c4a78",
    "primary_output": "allow_entry",
    "unused_inputs": (),
    "subcircuits": (),
}

# Stable ID -> generated identifier (reversible mapping; names are exact, escaped strings).
IDENTIFIER_MAP = {
    "v_79df34978043": {"kind": "input", "name": "member", "identifier": "input_member"},
    "v_8afde06f51e3": {"kind": "input", "name": "invited", "identifier": "input_invited"},
    "v_60b2536f5dc8": {"kind": "input", "name": "banned", "identifier": "input_banned"},
    "f_ae8686d89791": {"kind": "output", "name": "allow_entry", "identifier": "output_allow_entry"},
}

INPUT_NAMES = ("member", "invited", "banned")
OUTPUT_NAMES = ("allow_entry",)
ASSUMPTIONS = ()

_DECLARED_INPUTS = frozenset(INPUT_NAMES)
_SCOPE_INPUTS = ()
_ASSUMPTION_FORMULAS = {entry["name"]: entry["formula"] for entry in ASSUMPTIONS}


class InputError(ValueError):
    """Raised when inputs are missing, undeclared, or not exactly True/False.

    Every required input must satisfy type(value) is bool. Missing inputs, None, strings,
    integers (including 0 and 1), and keys that are not declared inputs are rejected before
    anything is evaluated. A missing input is never treated as False. The individual problems
    are listed in the problems attribute.
    """

    def __init__(self, problems):
        self.problems = tuple(problems)
        super().__init__("Invalid inputs: " + "; ".join(self.problems))


class OutOfScopeError(ValueError):
    """Raised when the inputs violate the model's assumptions (its declared scope).

    Outside its assumptions the rule has no decision: this error is never a False result.
    The names of the violated assumptions are in the violated attribute.
    """

    def __init__(self, violated):
        self.violated = tuple(violated)
        details = ", ".join(name + " (" + _ASSUMPTION_FORMULAS.get(name, "?") + ")" for name in self.violated)
        super().__init__(
            "Out of scope: the inputs violate "
            + ("assumption " if len(self.violated) == 1 else "assumptions ")
            + details
            + ". The rule has no decision outside its assumptions; this is not a False result."
        )


def _short_repr(value: object) -> str:
    text = repr(value)
    return text if len(text) <= 60 else text[:57] + "..."


def _checked_inputs(inputs: Mapping[str, bool], required: Tuple[str, ...], check_scope: bool) -> Dict[str, bool]:
    """Validate inputs strictly before anything is evaluated and return a plain copy."""
    if type(check_scope) is not bool:
        raise TypeError("check_scope must be True or False")
    if not isinstance(inputs, _abc.Mapping):
        raise InputError(["inputs must be a mapping from input names to True/False, got " + type(inputs).__name__])
    problems = []
    for key in inputs:
        if type(key) is not str or key not in _DECLARED_INPUTS:
            declared = ", ".join(repr(name) for name in INPUT_NAMES) or "none"
            problems.append("undeclared input " + _short_repr(key) + " (declared inputs: " + declared + ")")
    needed = tuple(required) + (_SCOPE_INPUTS if check_scope else ())
    for name in needed:
        if name not in inputs:
            problems.append("missing required input " + repr(name))
    for key, value in inputs.items():
        if type(key) is str and key in _DECLARED_INPUTS and type(value) is not bool:
            problems.append(
                "input " + repr(key) + " must be True or False (type bool), got "
                + type(value).__name__ + " " + _short_repr(value)
            )
    if problems:
        raise InputError(list(dict.fromkeys(problems)))
    return dict(inputs.items())


def _require_bool_args(function: str, pairs: Tuple[Tuple[str, object], ...]) -> None:
    problems = [
        "argument " + repr(name) + " of " + function + " must be True or False (type bool), got "
        + type(value).__name__ + " " + _short_repr(value)
        for name, value in pairs
        if type(value) is not bool
    ]
    if problems:
        raise InputError(problems)


def minterm_index(*values: bool) -> int:
    """Row index of an assignment over a declared variable order.

    The first value is the most significant bit, so all-False is row 0. Used for indexed
    minterm (sum) and maxterm (product) forms.
    """
    index = 0
    for value in values:
        if type(value) is not bool:
            raise InputError(["minterm_index() takes True/False values, got " + type(value).__name__ + " " + _short_repr(value)])
        index = index * 2 + (1 if value else 0)
    return index


def _scope_values(values: Dict[str, bool]) -> Tuple[Tuple[str, bool], ...]:
    """Value of every enabled, confirmed assumption for validated inputs, in declared order."""
    return ()


def _require_in_scope(values: Dict[str, bool]) -> None:
    violated = tuple(name for name, holds in _scope_values(values) if not holds)
    if violated:
        raise OutOfScopeError(violated)


def in_scope(inputs: Mapping[str, bool]) -> bool:
    """True when the inputs satisfy every assumption (the model's declared scope).

    Requires the inputs the assumptions read; raises InputError for invalid inputs.
    """
    values = _checked_inputs(inputs, (), True)
    return all(holds for _, holds in _scope_values(values))


# ---- Formula bodies (inputs are validated by the public functions below) ----


def _compute_output_allow_entry(input_member: bool, input_invited: bool, input_banned: bool) -> bool:
    """Decision output 'allow_entry': (member OR invited) AND NOT banned"""
    return (input_member or input_invited) and (not input_banned)


# ---- Public API ----


def output_allow_entry(inputs: Mapping[str, bool], *, check_scope: bool = True) -> bool:
    """Decision output 'allow_entry' (stable ID f_ae8686d89791).

    'allow_entry' := (member OR invited) AND NOT banned

    Required inputs: 'member', 'invited', 'banned'.
    Raises InputError for missing, undeclared, or non-bool inputs, and OutOfScopeError
    when check_scope is True and the inputs violate an assumption.
    """
    values = _checked_inputs(inputs, ("member", "invited", "banned"), check_scope)
    if check_scope:
        _require_in_scope(values)
    output_allow_entry_value = _compute_output_allow_entry(values["member"], values["invited"], values["banned"])
    return output_allow_entry_value


def evaluate(inputs: Mapping[str, bool], *, check_scope: bool = True) -> Dict[str, bool]:
    """Evaluate every output (declared order); each output is computed once.

    Required inputs: 'member', 'invited', 'banned'.
    Raises InputError for missing, undeclared, or non-bool inputs, and OutOfScopeError
    when check_scope is True and the inputs violate an assumption.
    """
    values = _checked_inputs(inputs, ("member", "invited", "banned"), check_scope)
    if check_scope:
        _require_in_scope(values)
    output_allow_entry_value = _compute_output_allow_entry(values["member"], values["invited"], values["banned"])
    return {
        "allow_entry": output_allow_entry_value,
    }

The common slip

Writing if flag == True: or passing 1 for a Boolean. Both run in Python, and the second is exactly what the export's input contract rejects, because the rule was written over two values, not over integers.

Questions

Does the export run the rule or verify it?

It evaluates the validated model and nothing more. Its own docstring says that evaluating examples does not verify the rule; the checks on this site and in the app are what establish properties of the rule.

Why no implication operator?

Python has none. A -> B becomes (not a) or b, which is the implication elimination law; the export applies it for you.

Related

See also

Languages

Generated from the Tangibool engine, semantics tangibool-semantics/1, engine 1.0.0, build . Every table, map, simplification and verdict on these pages was computed by the Tangibool engine when the site was built, and every claim was re-checked by the same exact checker the app uses. Limits are stated where they apply. © 2026 Foreranger LTD.