Home > OS >  "Index out of range" error in Python when using for loop and conditionals to reject a valu
"Index out of range" error in Python when using for loop and conditionals to reject a valu

Time:10-23

I'm extremely new to Python and coding in general. This program is trying to take a list of 6 input numbers and run each through an equation against an already initialized list of 6 numbers. However I also want to reject any user input that is less or equal to 0.

Resistance = [12, 16, 27, 39, 56, 81]
Current = []
Power = []

print("Enter 6 positive values for current:")
for x in range(6):
    Current.append(eval(input()))
    if (Current[x]) > 0:
        Power.append(Current[x])
        Power[x] = (Power[x]**2) * Resistance[x]
    else:
        print("Positive values only.")
        Current.append(eval(input("enter again: ")))

print(Resistance)
print(Current)
print(Power)

My first if statement works when all positive, but if a negative is rejected, I get this error.

    Power[x] = (Power[x]**2) * Resistance[x]
IndexError: list index out of range

Either something is wrong with my conditional, or maybe the two indexes are off from each other after the else statement? I've looked at answers and keep poking at it, but I'm not sure where to go from here.

CodePudding user response:

The "Power" list doesn't keep up with 'x' because the code trying to get x-th value out of it despite the fact that it doesn't exist.

So, I suggest that the code might be enhaced in two ways.

  1. Don't change lists before you are sure that the input is right. So, utilize an intermediate variable for input.

  2. The code lets the user to make a mistake only once. So, I think it's better to "loop" the validation part.

Blockquote

Resistance = [12, 16, 27, 39, 56, 81]
Current = []
Power = []

print("Enter 6 positive values for current:")
for x in range(6):
    _m = eval(input())
    while _m <= 0:
        print("Positive values only.")
        _m = eval(input("enter again:"))
    Current.append(_m)
    Power.append(_m)
    Power[x] = (Power[x]**2) * Resistance[x]

print(Resistance)
print(Current)
print(Power)
  • Related