Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+6 votes

Here is the part of my code:

 totStudents=0
    for num in range(1,numSections+1):
        numStudents=int(input("Number of students in section " + str(num) +":"))
        totStudents=numStudents

The problem is that the "totStudents" gets overwritten every loop, so I can't figure out how to add up the total.

asked in CSC201 Spring 2021 by (1 point)

1 Answer

+2 votes

That's right -- for the accumulator pattern, it's important that you update the value of the accumulator variable (totStudents) each time through the loop, but you don't just want to set it to be EQUAL to the current number of students. You want to assign it to whatever it was before (totStudents) PLUS the new number of students, so that it accumulates more students each time through the loop.

In the example from class, we did

for i in range(...):
    theSum = theSum + i * i    

where i was the FOR loop variable going through the range of odd numbers.

Or alternatively, if we used odd as the FOR loop variable, then:

for odd in range(...):
    oddSquared = odd * odd
    theSum = theSum + oddSquared
answered by (508 points)
+1

Hi,
I think Dr.Forrest Stonedahl gave the appropriate answer and i don't have anything to add on that!!

...