-7

when we have to add in python via for loops then we have to type something like this:

>>> list(range(1,10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> total=0
... for element in range(1,10) :
...     total+=element
>>> print(total)
45

But i tried doing something else, i did not defined total in the benign and later just defined total as (total=element). and when i print total then every time 4 is coming no matter which number sequence i have. Can any one explain the reason that why every time 4 is coming?

Ravi Kumar Yadav
  • 193
  • 2
  • 15
roxaite
  • 111

3 Answers3

1

Why do you need for loops for that?

print(sum(range(10))

The thing, you've said did not really work, because that's the way for loop works. It replaced total with the element it used right now.

Andrii Chumakov
  • 279
  • 3
  • 12
0

You replaced total += e with total = e. So only the last value is used.

Eugene Primako
  • 2,767
  • 9
  • 26
  • 35
0

You have a list a = [1,2,3,4] and total = 0 Then, you are iteration the list

for e in a:
    total = a
print (total)

In every iteration the value of total is replacing with a and at the last iteration the value of a (= 4) is replacing the previous value of total. That's why it's printing 4 every time.

If you want to get the total value just replace

total = a

with

total += a
Sudarshan
  • 938
  • 14
  • 27