Python (3.1) - How do I print the last sum only?

Announcements, comments, ideas, feedback, and "How do I... ?" questions
Post Reply
The-Moose-Trainer
Posts: 3
Joined: Wed Mar 02, 2011 2:04 am

Python (3.1) - How do I print the last sum only?

Post by The-Moose-Trainer »

Okay, so in a lot of these problems, you need to find the sum of something, and the way i do this, python (3.1) prints the sum at each point i have a different x. so for example, my code looks like this:
#find sum of even values up to four million
x, y = (1, 1)
l = []
while x < 4 * (10 ** 6):
x, y = (y, x + y)
if x % 2 == 0:
l.append(x)
print(sum(l))
and my output is:
2
10
44
188
798
3382
14328
60696
257114
1089154
4613732
I only want that last number.
How do i do this?
TripleM
Posts: 384
Joined: Fri Sep 12, 2008 3:31 am

Re: Python (3.1) - How do I print the last sum only?

Post by TripleM »

It's printing it every time because you've got it executing the print statement every time inside that loop. If you just want it to output once at the end, move your print statement to be outside the loop at the end (ie remove the indentation before the print line).
Last edited by TripleM on Sun Mar 06, 2011 9:54 pm, edited 1 time in total.
The-Moose-Trainer
Posts: 3
Joined: Wed Mar 02, 2011 2:04 am

Re: Python (3.1) - How do I print the last sum only?

Post by The-Moose-Trainer »

wow. That's a dim move on my part. thanks a ton though. there isn't any info on this i could find.
Post Reply