Search code examples
pythonif-statementcomparison

Python: Convert a Letter Grade to its corresponding integer value


I am attempting to troubleshoot the errors in this code.

The program is supposed to handle as many students as the user indicates are in the class. Receive a letter grade: A, B, C, D, F for each student. Finally it will calculate and display the class average.

My code so far:

students = int(input('How many students: '))
total_sum = 0
for n in range(students):
    Letter = input('Enter grades: ')
    Letter_int = Letter
if Letter == "A":
    Letter_int == int(80)
elif Letter == "B":
    Letter_int == int(70)
elif Letter == "C":
    Letter_int == int(60)
elif Letter == "D":
    Letter_int == int(50)
elif Letter == "F":
    Letter_int == int(40)
    total_sum += Letter_int
avg = total_sum/students
print('Average of this/these', students, 'student(s) is:', avg)

The code isn't adding the integer value of the letter grades, the sum always returns as 0 or TypeError: unsupported operand type(s) for +=: 'int' and 'str'. I am a python novice and I could use some assistance.


Solution

  • Here is your code improved and made work. Use it, but please read the comments I provided and analyze what parts I have changed. Also, it would be good to revise Python documentation as others mentioned. Especially indentation and it's meaning in Python.

    students = int(input('How many students: '))
    total_sum = 0
    for n in range(students):
        Letter = input('Enter grades: ')
        Letter_int = 0 # here you better initialize with integer not string
        if Letter == "A": # this condition needs to be indented - you want it to be executed
                          # in every iteration of for loop
            Letter_int = 80 # the assignment in Python is done by "=" not "==" (that would be comparison) 
        elif Letter == "B": 
            Letter_int = 70 # you do not need to do int(70), 70 is already an integer
        elif Letter == "C":
            Letter_int = 60
        elif Letter == "D":
            Letter_int = 50
        elif Letter == "F":
            Letter_int = 40
        total_sum += Letter_int # this cannot happen inside elif clause - this way it would only be
                                # executed when F grade is provided
        avg = total_sum/students
        print('Average of this/these', students, 'student(s) is:', avg)