-4

For example array [1, 2, 4, 5, 6] it must be 1 + 2 + 4 + 5 + 6. so how is the result in these loops? so look below the script


    number = [1, 2, 4, 5, 6]
    
    for x in number:
        x + x
    
    print(x)

1 Answers1

-3

Just add a += and a new variable like so:

number = [1, 2, 4, 5, 6]
y = 0 #new variable (output variable)
for x in number:
    y += x #add = sign here

print(y)

Output:

18

But it would be better to use:

y = sum(number)
print(y)

Output:

18
Eli Harold
  • 2,280
  • 1
  • 3
  • 22