0

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.

2
  • 1
    It's numbers[index]. Commented Mar 21, 2021 at 16:18
  • oh I see thank you! Commented Mar 21, 2021 at 16:23

4 Answers 4

2

Change index[numbers] to numbers[index]

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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)

1 Comment

Thank you for your answer, now I understand what I did wrong.
0

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

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.