TheAlgorithms/Python · error · ValueError
area_circle() only accepts non-negative values
Error message
area_circle() only accepts non-negative values
What it means
area_circle() raises this ValueError when radius is negative. The library requires radius >= 0 before returning pi * radius**2. Because squaring would silently hide a negative input, the guard exists specifically to surface that mistake.
Source
Thrown at maths/area.py:451
def area_circle(radius: float) -> float:
"""
Calculate the area of a circle.
>>> area_circle(20)
1256.6370614359173
>>> area_circle(1.6)
8.042477193189871
>>> area_circle(0)
0.0
>>> area_circle(-1)
Traceback (most recent call last):
...
ValueError: area_circle() only accepts non-negative values
"""
if radius < 0:
raise ValueError("area_circle() only accepts non-negative values")
return pi * radius**2
def area_ellipse(radius_x: float, radius_y: float) -> float:
"""
Calculate the area of a ellipse.
>>> area_ellipse(10, 10)
314.1592653589793
>>> area_ellipse(10, 20)
628.3185307179587
>>> area_ellipse(0, 0)
0.0
>>> area_ellipse(1.6, 2.6)
13.06902543893354
>>> area_ellipse(-10, 20)
Traceback (most recent call last):
...
View on GitHub (pinned to f5988cc097)
Solutions
- Validate radius >= 0 before the call and correct the upstream sign error.
- Pass abs(radius) when the value is a magnitude with a sign artifact.
- Restrict input types in forms/CLI (reject negatives at parse time).
- Catch ValueError to emit a clear message.
Example fix
// before area = area_circle(r) # r = point_x - center_x, may be negative # after area = area_circle(abs(point_x - center_x))
Defensive patterns
Strategy: validation
Validate before calling
if radius < 0:
raise ValueError(f'circle radius must be >= 0, got {radius}')
area = area_circle(radius) Type guard
def is_valid_radius(r: object) -> bool:
return isinstance(r, (int, float)) and not isinstance(r, bool) and r >= 0 Try / catch
try:
area = area_circle(radius)
except ValueError as e:
raise ValueError(f'invalid circle radius {radius!r}: {e}') from e Prevention
- Restrict CLI/form radius inputs to non-negative parsers.
- Never rely on squaring to neutralize a negative radius.
When it happens
Trigger: Calling area_circle(radius) with radius < 0, e.g. area_circle(-1).
Common situations: Radius computed as a coordinate delta; user/CLI input not restricted to non-negative; data files where '-' marks missing entries.
Related errors
- surface_area_cube() only accepts non-negative values
- surface_area_cuboid() only accepts non-negative values
- surface_area_sphere() only accepts non-negative values
- surface_area_hemisphere() only accepts non-negative values
- surface_area_cone() only accepts non-negative values
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/24161d7027adffaa.
Report an issue: GitHub.