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

Time:10-11

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: ∑i=1ni2=12 22 32 … n2, 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

CodePudding user response:

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.

CodePudding user response:

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

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

Output:

338350

CodePudding user response:

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
  • Related