0

I am trying to get a sum of all elements using while loop.

from numpy import *
x = array([1, 23, 43, 72, 87, 56, 98, 33])
def sum_x(x):
    sum = 0
    for i in x:
        sum += i
    return sum
print(sum_x(x))

This is the code I made for 'for loop'. I would like to change it to 'while loop' code. Please help me out! I have no idea how to add an element to an element in while loop.

4
  • It works with print(sum_x()). I am getting same result as sum(x). Commented Nov 4, 2018 at 3:04
  • Oh I missed a line which is (sum += i). However, I just figured it out the answer thanks tho. Commented Nov 4, 2018 at 3:08
  • I fixed a code in the question. It may look ugly, but it works. Commented Nov 4, 2018 at 3:23
  • You don't need numpy or array for this. A regular (built-in) list works fine. Commented Nov 4, 2018 at 4:25

2 Answers 2

1

Clean while loop:

def sum_x(x):
    i = 0
    res = 0
    while i < len(x):
        res += x[i]
        i += 1
    return res

>>> sum_x(np.arange(100))
4950
Sign up to request clarification or add additional context in comments.

Comments

1

You actually don't need to use any looping structure, just use:

x = array([1, 23, 43, 72, 87, 56, 98, 33])
print(sum(x))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.