TheAlgorithms/Python · error · ValueError
Resistor at index {index} has a negative value!
Error message
Resistor at index {index} has a negative value! What it means
Raised by resistor_series() in electronics/resistor_equivalence.py when any element of the resistors list is negative. Unlike the parallel function, zero is allowed here (a 0-ohm link is physically fine in a series chain); only strictly negative values are rejected, again naming the 0-based index of the offending element. Note the check fires after the value is added to the running sum, but since it raises, the partial sum is discarded.
Source
Thrown at electronics/resistor_equivalence.py:49
def resistor_series(resistors: list[float]) -> float:
"""
Req = R1 + R2 + ... + Rn
Calculate the equivalent resistance for any number of resistors in parallel.
>>> resistor_series([3.21389, 2, 3])
8.21389
>>> resistor_series([3.21389, 2, -3])
Traceback (most recent call last):
...
ValueError: Resistor at index 2 has a negative value!
"""
sum_r = 0.00
for index, resistor in enumerate(resistors):
sum_r += resistor
if resistor < 0:
msg = f"Resistor at index {index} has a negative value!"
raise ValueError(msg)
return sum_r
if __name__ == "__main__":
import doctest
doctest.testmod()
View on GitHub (pinned to f5988cc097)
Solutions
- Sanitize inputs: take abs() only if you know the sign is a data-entry artifact, otherwise reject the record.
- Validate `all(r >= 0 for r in resistors)` before calling if you want to fail fast with your own message.
- Catch ValueError and log the reported index to locate the bad row in the source data.
Example fix
# before r = resistor_series([3.21389, 2, -3]) # ValueError: index 2 # after r = resistor_series([3.21389, 2, 3])
Defensive patterns
Strategy: validation
Validate before calling
if any(r < 0 for r in resistors):
bad = [i for i, r in enumerate(resistors) if r < 0]
raise UserInputError(f"Negative resistance at indices {bad}; check sign of parsed values") Type guard
def all_non_negative(vals: list[float]) -> bool:
return all(r >= 0 for r in vals) # 0 ohm links are valid in series Try / catch
try:
total = resistor_series(resistors)
except ValueError as exc:
total = None
log_bad_row(str(exc)) Prevention
- Validate sign at CSV parse time.
- Note series allows 0 but parallel does not — do not share one validator blindly.
- Watch for -0.0 from floating-point cleanup.
When it happens
Trigger: resistor_series([3.21389, 2, -3]) — any negative element; sign errors in parsed data such as '-4.7' meaning 4.7 ohms; subtraction artifacts like -0.0 from floating-point cleanup.
Common situations: Datasheets or CSVs encoding tolerance as signed deltas that get merged into the value column; unit conversion bugs producing negatives; reusing validation logic written for resistor_parallel (which also rejects 0) and being surprised 0 passes here.
Related errors
- {color} is not a valid color for significant figure bands
- {total_number_of_bands} is not a valid number of bands
- {type_of_band} is not valid for a {total_number_of_bands} ba
- {color} is not a valid color
- Expecting {number_of_bands} colors, provided {len(colors)} c
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/4d16975055ef2076.
Report an issue: GitHub.