Reputation: 81
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?
Upvotes: 0
Views: 91
Reputation: 263
Changing the condition to numSelector <= len(nums)-1 or numSelector < len(nums) will do for you.
Upvotes: 0
Reputation: 6998
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.
Upvotes: 0
Reputation: 325
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
Upvotes: 4