TheAlgorithms/Python · error · ValueError

{token} is neither a number nor a valid operator

Error message

{token} is neither a number nor a valid operator

What it means

Raised by convert_token() in data_structures/stacks/postfix_evaluation.py:61 when a token is neither in the OPERATORS dict ('+','-','*','/','^','%') nor parseable by float(). It is the input-validation stage of evaluate(): each space-separated token must already be a number or a known operator symbol.

Source

Thrown at data_structures/stacks/postfix_evaluation.py:61

    returns the data as it is with a False flag. This function also serves as a check
    of whether the input is a number or not.

    Parameters
    ----------
    token: The data that needs to be converted to the appropriate operator or number.

    Returns
    -------
    float or str
        Returns a float if `token` is a number or a str if `token` is an operator
    """
    if token in OPERATORS:
        return token
    try:
        return float(token)
    except ValueError:
        msg = f"{token} is neither a number nor a valid operator"
        raise ValueError(msg)


def evaluate(post_fix: list[str], verbose: bool = False) -> float:
    """
    Evaluate postfix expression using a stack.
    >>> evaluate(["0"])
    0.0
    >>> evaluate(["-0"])
    -0.0
    >>> evaluate(["1"])
    1.0
    >>> evaluate(["-1"])
    -1.0
    >>> evaluate(["-1.1"])
    -1.1
    >>> evaluate(["2", "1", "+", "3", "*"])
    9.0
    >>> evaluate(["2", "1.9", "+", "3", "*"])

View on GitHub (pinned to f5988cc097)

Solutions

  1. Tokenize with expression.split() (no argument) so empty tokens never occur
  2. Normalize operators before evaluation (e.g. '**' -> '^')
  3. Catch ValueError and report the offending token back to the user

Example fix

// before
tokens = expression.split(' ')  # '1  +  2' -> ['', '+', '', '+', '2']

# after
tokens = expression.split()  # collapses all whitespace, no empty tokens
Defensive patterns

Strategy: validation

Validate before calling

tokens = expression.split()  # no arg: collapses all whitespace, no '' tokens
tokens = [t.replace('**', '^') for t in tokens]

Type guard

from data_structures.stacks.postfix_evaluation import OPERATORS

def all_tokens_valid(tokens: list[str]) -> bool:
    return all(t in OPERATORS or _is_float(t) for t in tokens)

def _is_float(t: str) -> bool:
    try:
        float(t)
        return True
    except ValueError:
        return False

Try / catch

try:
    result = evaluate(tokens)
except ValueError as e:
    if 'neither a number nor a valid operator' not in str(e):
        raise
    # report offending token from the message back to the user

Prevention

When it happens

Trigger: evaluate(['2','&','3']), passing '**' instead of '^', comma-formatted numbers like '1,000', or an empty token from double spaces ('1 + 2'.split(' ') yields '').

Common situations: Splitting on a single space instead of str.split() (which collapses whitespace), locale-specific number formats, or using operators the evaluator never defined.

Related errors


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