Loops in Python work differently than you think.
Let's start with a simpler loop example. When you write:
for i in range(1, 4):
print(i)
it is as if you actually wrote:
i = 1
print(i)
i = 2
print(i)
i = 3
print(i)
The loop body is print(i)
, so Python takes print(i)
and runs it once for each i
in the range.
So, since range(1, 4)
contains the numbers 1, 2, and 3, first i
got assigned the value 1, then the loop body was executed, then i
got assigned the value 2, then the loop body was executed again, and so on.
Think of a loop as just shorthand for copy-pasting the same code a bunch of times.
So in your specific problem, your code:
sum=0
for i in range(10,91):
sum=sum+i
print(sum)
is as if you copy-pasted the same code like this:
sum=0
i=10
sum=sum+i
print(sum)
i=11
sum=sum+i
print(sum)
i=12
sum=sum+i
print(sum)
i=13
sum=sum+i
print(sum)
...
i=88
sum=sum+i
print(sum)
i=89
sum=sum+i
print(sum)
i=90
sum=sum+i
print(sum)
Notice the print(sum)
copy-pasted over and over again.
And that is why your code has the output that it does.
Hopefully that helps you understand why the other answer suggested changing it to this instead:
sum = 0
for i in range(10,91):
sum = sum + i
print(sum)
Because when you take the print
out of the loop body, it's as if you're only copy-pasting the sum=sum+i
:
sum=0
i=10
sum=sum+i
i=11
sum=sum+i
i=12
sum=sum+i
i=13
sum=sum+i
...
i=88
sum=sum+i
i=89
sum=sum+i
i=90
sum=sum+i
print(sum)
Notice that there's only one print at the end now.
Also!
You can use this same thinking to understand what went wrong in your other question which was "closed as duplicate"!
There you wrote:
for i in data:
print(max(i))
which is as-if you wrote:
i=data[0]
print(max(i))
i=data[1]
print(max(i))
i=data[2]
print(max(i))
...
and so in that problem, you can see that max
only ever gets called with one integer from data
at a time.