How to ADD all printed numbers using for loop

#1

Code works perfect.

I just have a doubt about how to add all the numbers that the print statement prints. As in, I have this Print num ** 2 which prints all the numbers in a new line.

What if i want to ADD all those squared numbers and get a total of it? Thanks for the help in advance.

``````numbers  = [7, 9, 12, 54, 99]

print "This list contains: "

for num in numbers:
print num

for num in numbers:
print num ** 2``````

#2

Then you would add it in a variable like this:

``````count = 0
for num in numbers:
count = count + num``````

Or something along those lines.

#3

I did try that before but it just adds the numbers which are already in the list mentioned "numbers".

My question: I wanted to add all those squared numbers. For which what I think is that I have to first make a list of all those squared numbers and then use the FOR loop which you mentioned. Unfortunately, I am having problem in making a list of those numbers. Please help. Thank you!

#4

Whoops...I forgot you want to add the squared numbers. In that case, I would say do this:

``````squares = [ ]
for num in numbers:
squares.append(num ** 2)
count = 0
for numbers in squares:
count += num``````

#5

I'm sure that there's a better way to do this rather than what I just did, but I can't seem to rack my brain right now. Not to mention, I haven't slept for the past 26 hours, so I'm not the sharpest mind around right now.

#6

Hey friend,

It works! omg I am finally feeling better. Though I added a little different line of in it to make it more clear. Check below:

squares = []
for num in numbers:
squares.append(num ** 2)
count = 0
for num in squares:
count += num
print ("The sum of all squared number is: %s " % count)

#7

Bravo! And yeah, this does make it clearer:

#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.