TheAlgorithms/Python · error · ValueError

area_reg_polygon() only accepts integers greater than or equ

Error message

area_reg_polygon() only accepts integers greater than or equal to three as number of sides

What it means

area_reg_polygon() raises this ValueError when sides is not an int or is less than 3. A regular polygon needs at least 3 sides (triangle); the library also rejects floats like 4.0 and bools count only via isinstance quirks, because the formula (n * s^2) / (4 * tan(pi/n)) assumes an integer side count. This is a type-and-domain check, distinct from the separate negative-length check on the second parameter.

Source

Thrown at maths/area.py:545

three as number of sides
    >>> area_reg_polygon(-1, -2)
    Traceback (most recent call last):
        ...
    ValueError: area_reg_polygon() only accepts integers greater than or equal to \
three as number of sides
    >>> area_reg_polygon(5, -2)
    Traceback (most recent call last):
        ...
    ValueError: area_reg_polygon() only accepts non-negative values as \
length of a side
    >>> area_reg_polygon(-1, 2)
    Traceback (most recent call last):
        ...
    ValueError: area_reg_polygon() only accepts integers greater than or equal to \
three as number of sides
    """
    if not isinstance(sides, int) or sides < 3:
        raise ValueError(
            "area_reg_polygon() only accepts integers greater than or \
equal to three as number of sides"
        )
    elif length < 0:
        raise ValueError(
            "area_reg_polygon() only accepts non-negative values as \
length of a side"
        )
    return (sides * length**2) / (4 * tan(pi / sides))


if __name__ == "__main__":
    import doctest

    doctest.testmod(verbose=True)  # verbose so we can see methods missing tests

    print("[DEMO] Areas of various geometric shapes: \n")
    print(f"Rectangle: {area_rectangle(10, 20) = }")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Coerce to int explicitly when the value is integral: sides = int(round(sides)).
  2. Validate sides >= 3 before the call and reject bad config early.
  3. Convert numpy integers with int(sides) before calling.
  4. Catch ValueError and report the offending sides value.

Example fix

// before
area = area_reg_polygon(user_input, s)  # user_input is 4.0 (float from JSON)

# after
if not isinstance(sides, int) or sides < 3:
    sides = int(round(float(user_input)))
area = area_reg_polygon(sides, s)
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(sides, int) or isinstance(sides, bool) or sides < 3:
    raise ValueError(f'sides must be an int >= 3, got {sides!r}')
area = area_reg_polygon(sides, length)

Type guard

def is_valid_polygon_sides(n: object) -> bool:
    """Type guard: n is a true int (not bool) with value >= 3."""
    return isinstance(n, int) and not isinstance(n, bool) and n >= 3

Try / catch

try:
    area = area_reg_polygon(sides, length)
except ValueError as e:
    raise ValueError(f'invalid polygon params (sides={sides!r}, length={length!r}): {e}') from e

Prevention

When it happens

Trigger: Calling area_reg_polygon(sides, length) with sides as a non-int (e.g. 4.5 or '6') or an int < 3 (e.g. -1, 0, 1, 2), e.g. area_reg_polygon(-1, 2) or area_reg_polygon(4.0, 2). Passing a numpy integer can also fail since isinstance(np.int64(4), int) is False on most platforms.

Common situations: User input parsed as float ('4.0' from a form) and passed straight in; numpy/pandas integer types flowing into the function; loop variables starting at 0 or 1; JSON configs where the side count deserializes as float.

Related errors


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