how do i use For loop to calculate and print the sums from within the loop? Python

Question:

Hi all im brand new to programming obviously. As a part of my physics degree i have to do programming wonder if anyone can explain the following problem, this is not a piece of coursework or anything that i will be graded on so no im not cheating,im trying to speak to people who better understand this stuff who would like to explain to me the concept of my required task. The university seems to have restricted help available for this module so thought I’d ask the experts online.

In the cell below, by using the for loop, calculate and print the following sum (the sum of the square of first n natural numbers):
∑i = 1^2 + 2^2 + 3^2 + … + n^2,
where n=100 . (This means: loop over all numbers from 1 to 100, square each of them, and add them all together)

my current code is :

for n in range(0,101):
  n  = n**2
  print(n) 

#now this prints all the squared numbers but how do i tell it to add them all up? the sum function doesnt appear to work for this task. id appreciate any help! – JH

Asked By: Jed Hennessy

||

Answers:

Almost there,

total = 0

for n in range(0,101):
    total  += n**2
    print(total) 

You missed the plus sign, you are just setting n to be the current number, you want to add it in every loop. So use a new variable called total and add into it.

Answered By: anarchy

The built-in sum() function is probably the best solution for this:

print(sum(x*x for x in range(1, 101)))

Output:

338350
Answered By: OldBill

You Can Simply Follow This Code

all_Sum = 0 #first create a variable to store all sum 

#make a loop
for i in range(0,101): #making loop go from 0 to 100
    all_Sum += i**2 #we are first getting square of number then added to variable

print(all_Sum)    #printing all sum
Answered By: CYCNO
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.