0

I'm having problems with this block of code:

while numSelector <= len(nums)+1:
    average = average + nums[numSelector]
    numSelector += 1

and I'm getting this error from the code:

Traceback (most recent call last): File "C:\Users\nghia_000\Documents\Programming\Python27\AveragingCalculator.py", line 11, in average = average + nums[numSelector] IndexError: list index out of range

Any idea how to fix this?

3 Answers 3

4

If the length of a list is n, then it contains elements at indices 0 to n-1. Try:

numSelector = 0
while numSelector < len(nums):
    average = average + nums[numSelector]
    numSelector += 1

A better way would be to directly iterate over the numbers present in the list using a for loop:

for num in nums:
    average += num
Sign up to request clarification or add additional context in comments.

Comments

0

Suppose len(nums) == 5. Then the line:

while numSelector <= len(nums) + 1:

means "keep going until numSelector is no more than 6. But numSelector only has five elements in it -- 0, 1, 2, 3, 4.

Comments

0

Changing the condition to numSelector <= len(nums)-1 or numSelector < len(nums) will do for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.