Reputation: 37
So I tried to sum the array with a while loop, something is going wrong. I get this type of error:
total = total + index[numbers] TypeError: 'int' object is not subscriptable
Here's my code
numbers = [1,5,6,3,7,7,8]
index = 0
total = 0
while index <= len(numbers):
total = total + index[numbers]
index += 1
The answer that I should get is 37, with using the while loop.
Upvotes: 0
Views: 3598
Reputation: 176
The answer Ailrk provides is correct, I just want to add that in Python you can just use sum(numbers)
to find the sum of the array.
Upvotes: 1
Reputation: 15568
You can do:
numbers = [1,5,6,3,7,7,8]
total = 0
while numbers:
total = total + numbers.pop()
print(total)
While we have a number in numbers, pop it our and add to total. The while loop will break when all numbers are popped as an empty list is False in Python
Upvotes: 0
Reputation: 46
Change <= to < and index[numbers] to numbers[index]
numbers = [1,5,6,3,7,7,8]
index = 0
total = 0
while index < len(numbers):
total = total + numbers[index]
index += 1
print(total)
Try this code.
Use < instead of <= and numbers[index] instead of index[numbers]
You can do this using sum() function.
numbers = [1,5,6,3,7,7,8]
total = sum(numbers)
print(total)
Upvotes: 0