TheAlgorithms/Python · error · ValueError

area_square() only accepts non-negative values

Error message

area_square() only accepts non-negative values

What it means

area_square() raises this ValueError when side_length is negative. A square's side is a physical length; the library checks side_length >= 0 before returning side_length**2. The guard prevents a negative input from being silently squared into a plausible-looking but invalid area.

Source

Thrown at maths/area.py:283


def area_square(side_length: float) -> float:
    """
    Calculate the area of a square.

    >>> area_square(10)
    100
    >>> area_square(0)
    0
    >>> area_square(1.6)
    2.5600000000000005
    >>> area_square(-1)
    Traceback (most recent call last):
        ...
    ValueError: area_square() only accepts non-negative values
    """
    if side_length < 0:
        raise ValueError("area_square() only accepts non-negative values")
    return side_length**2


def area_triangle(base: float, height: float) -> float:
    """
    Calculate the area of a triangle given the base and height.

    >>> area_triangle(10, 10)
    50.0
    >>> area_triangle(1.6, 2.6)
    2.08
    >>> area_triangle(0, 0)
    0.0
    >>> area_triangle(-1, -2)
    Traceback (most recent call last):
        ...
    ValueError: area_triangle() only accepts non-negative values
    >>> area_triangle(1, -2)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check side_length >= 0 before the call and fix the negative source.
  2. Use abs() if the sign is an artifact of how the length was computed.
  3. Validate form/CLI input rejects negatives at entry.
  4. Catch ValueError to present a clear error.

Example fix

// before
area = area_square(side)  # side may be negative from user input

# after
side = float(input('side: '))
if side < 0:
    raise ValueError('side must be non-negative')
area = area_square(side)
Defensive patterns

Strategy: validation

Validate before calling

if side_length < 0:
    raise ValueError(f'square side must be >= 0, got {side_length}')
area = area_square(side_length)

Type guard

def is_valid_side(x: object) -> bool:
    return isinstance(x, (int, float)) and not isinstance(x, bool) and x >= 0

Try / catch

try:
    area = area_square(side_length)
except ValueError as e:
    raise ValueError(f'invalid square input {side_length!r}: {e}') from e

Prevention

When it happens

Trigger: Calling area_square(side_length) with side_length < 0, e.g. area_square(-1).

Common situations: Passing deltas or differences as sides; user input not validated for sign; data feeds that encode missing values as negative numbers.

Related errors


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