Dividing a string by an integer to get GPA calculation

129 Views Asked by At

I am working on Python and am writing a program where the user inputs how many courses they would like to calculate. Then the program is supposed to take the appended items (the strings) and then divide them by how many courses they would like, in other words the total (integer). I cannot seem to figure out a way to implement this properly, any help? The issue is under If value = 1.

if (value == 1):
    selection = int(input("How many classses would you like to include?\n"))
    for i in range (0,selection):
        print("What is the grade of the class?")
        item = (input())
        grades.append(item)
        GPA_list = [sum(item)/selection for i in grades]
        print(GPA_list)
    
1

There are 1 best solutions below

2
Samwise On

You can simplify this quite a bit by using mean, which does the summing and dividing for you:

>>> from statistics import mean
>>> print(mean(
...     float(input(
...         "What is the grade of the class?\n"
...     )) for _ in range(int(input(
...         "How many classes would you like to include?\n"
...     )))
... ))
How many classes would you like to include?
5
What is the grade of the class?
4
What is the grade of the class?
3
What is the grade of the class?
4
What is the grade of the class?
2
What is the grade of the class?
4
3.4

To fix your existing code, all you need to do is make sure to convert item to a float and then call sum on grades rather than each item:

grades = []
selection = int(input("How many classses would you like to include?\n"))
for i in range(0, selection):
    print("What is the grade of the class?")
    item = float(input())
    grades.append(item)
    GPA_list = sum(grades) / selection
    print(GPA_list)

Note that your code prints a fraction of the average at each step in the loop until finally printing the correct result in the last iteration; if you want to fix this as well, unindent the last two lines.