TheAlgorithms/Python · error · ValueError

guess value must be within the range of lower and higher val

Error message

guess value must be within the range of lower and higher value

What it means

Raised by guess_the_number when to_guess is not strictly inside the open interval (lower, higher). The search space of the binary search is [lower, higher], so the target must satisfy lower < to_guess < higher; endpoints themselves are rejected.

Source

Thrown at other/guess_the_number_search.py:117

    >>> guess_the_number(10, 1000, 5)
    Traceback (most recent call last):
        ...
    ValueError: guess value must be within the range of lower and higher value

    >>> guess_the_number(10000, 100, 5)
    Traceback (most recent call last):
        ...
    ValueError: argument value for lower and higher must be(lower > higher)
    """
    assert (
        isinstance(lower, int) and isinstance(higher, int) and isinstance(to_guess, int)
    ), 'argument values must be type of "int"'

    if lower > higher:
        raise ValueError("argument value for lower and higher must be(lower > higher)")

    if not lower < to_guess < higher:
        raise ValueError(
            "guess value must be within the range of lower and higher value"
        )

    def answer(number: int) -> str:
        """
        Returns value by comparing with entered `to_guess` number
        """
        if number > to_guess:
            return "high"
        elif number < to_guess:
            return "low"
        else:
            return "same"

    print("started...")

    last_lowest = lower
    last_highest = higher

View on GitHub (pinned to f5988cc097)

Solutions

  1. Choose a target strictly between the bounds, e.g. random.randint(lower + 1, higher - 1)
  2. Widen the bounds so the target is interior: lower < to_guess < higher
  3. If endpoints must be guessable, note this API forbids them — pick a different target

Example fix

# before
to_guess = random.randint(lower, higher)  # can equal a bound -> ValueError
guess_the_number(lower, higher, to_guess)

# after
to_guess = random.randint(lower + 1, higher - 1)
guess_the_number(lower, higher, to_guess)
Defensive patterns

Strategy: validation

Validate before calling

def valid_target(lower: int, higher: int, to_guess: int) -> bool:
    return lower < to_guess < higher  # strictly interior; endpoints rejected

Prevention

When it happens

Trigger: Calling guess_the_number(10, 100, 10) or guess_the_number(10, 100, 100) (target equal to a bound), or to_guess outside the interval entirely, e.g. guess_the_number(10, 100, 500).

Common situations: Off-by-one mistakes where the target is generated with inclusive random.randint(lower, higher) and lands on an endpoint, or hard-coded puzzle answers that drift out of the configured range.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/c06077e2df184755. Report an issue: GitHub.