Reputation: 31
Let's say I want to know the total sum of a list which goes from 0 to 100 which is 5050? I loop through my list:
c=0
for i in range(0,101):
c+=i
print(c)
The problem is I want just the last element not all of them.
Upvotes: 2
Views: 6174
Reputation: 1123
As per the code you provided here, you missed the indentation of the print statement, if you keep it this way
c=0
for i in range(0,101):
c+=i
print(c)
It will print all the sum because it is inside for loop as per the current indentation, but if you want only the final output, change the indentation of the print statement like below
c=0
for i in range(0,101):
c+=i
print(c)
Now it is not inside for loop, it will only print final value of the sum(c).
Upvotes: 0
Reputation: 5615
There's a python function just for this - sum
print(sum([x for x in range(1, 101)]))
Edit: To address the concern about "struggling to understand"
[x for x in range(1, 101)]
is called a list comprehension. They are used to create lists in a singular line, without using for
loops - python can be a functional programming language after all. [x for x in range(1, 101)]
returns a list from 1 to 100, that is-
[1, 2, 3, 4, 5, ......., 99, 100]
We skip 0 because it doesn't count in the sum anyway.
Now if you do sum()
on this list, it'll return the sum of all elements in the list.
Hence sum([for x in range (1, 101)])
returns the sum of all numbers from 1 to 100 (inclusive) and print
will print the final result.
Why use many lines when few do trick? :)
Remember, List Comprehension and sum()
are 2 very important tools in the python toolbox, everyone should know about these 2.
Upvotes: 2
Reputation: 1623
Just change the Print Indentation.
Try the below Code,
c=0
for i in range(0,101):
c+=i
print(c)
Upvotes: 1
Reputation: 529
You are printing the value of variable "c" in the loop. To print only the sum, remove the indentation of "print(c)". And you are doing "=+" but you should do "+=" to obtain the sum.
c=0
for i in range(0,101):
c+=i
print(c)
Upvotes: 3