Search code examples
pythonwhile-loopaverage

I'm trying to make a grade average system but with while loops, how can I individually get the outputs from the while loop?


This is what I've came up so far:

Is there like a way to individually get the output/answers from the while loop so I can add and divide them? Or is there another way like a for loop to access them? I'm quite new to coding so thanks in advance!


Solution

  • If you're trying to store multiple grades, and perform operations on them, then a list can help. You can define "grades" as a list variable before the while loop. Then after the loop you can use print() function to see what's in the list.

    Using a for loop, you can perform operations with each grade in the list. To get the sum of the grades you can define a "sum" variable and add each grade from the for loop.

    Based on what you've said, I think this is a good starting point:

    EDIT: Changed variable "sum" to "g_sum" because sum is a built-in Python method. Using a variable by the same name could pose a problem if you tried to use this method.

    unit = 0
    grades = [] # this is the list of grades
    
    while unit < 8:
        # append will add each grade to the list
        grades.append(int(input("Enter Grades: ")))
        unit += 1
    
    # printing all values in the list
    print(grades)
    
    # we can already get a denominator from the length of the list
    denominator = len(grades)
    
    # for loop to get sum of all grades in list
    g_sum = 0
    for g in grades:
        g_sum += g
    
    # now we can get the average
    average = g_sum / denominator
    
    # printing sum and average of grades
    print(f"Sum of grades: {g_sum}\nAverage of grades: {average}")