Search code examples
pythonfor-loopsum

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


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


Solution

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

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

    Output:

    338350