Skip to content Skip to sidebar Skip to footer

Sum Of Elements Using While Loop

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

Solution 1:

Clean while loop:

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

>>> sum_x(np.arange(100))
4950

Solution 2:

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))

Post a Comment for "Sum Of Elements Using While Loop"