He has the following code but he is getting the following error nboundLocalError: local variable 'grade' referenced before assignment, can anyone help please?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
def grade(overallmarks): percentage = overallmarks / 150 * 100 # Prints 'No Award' if the overall percentage mark is less than 45 if percentage < 45 :. grade = "No Award" # Prints the grade 'D' if the overall percentage mark is between 45 & 49 elif percentage > = 45 and percentage < = 49 : grade = "D" # Prints the grade 'C' if the overall percentage mark is between 50 & 59 elif percentage > = 50 and percentage < = 59 : grade = "C" # Prints the grade 'B' if the overall percentage mark is between 60 & 69 elif percentage > = 60 and percentage < = 69 : grade = "B" # Prints the grade 'A' if the overall percentage mark is 70 or over elif percentage > = 70 : grade = "A" return grade, percentage def main(): # Opens the studentgrades.csv file in read mode f = open ( "studentgrades.csv" ) # Reads all of the file lines and put them in a list rows = f.readlines() # The loop goes through all of the rows, one by one for counter in range ( len (rows)): # Extract the current line line = rows[counter].strip() # Splits and organises each line and saves in a list fields = line.split( "," ) student_name = fields[ 0 ] coursework = fields[ 1 ] prelim_mark = fields[ 2 ] # Set coursework to integer coursework = int (coursework) # Set prelim mark to integer prelim_mark = int (prelim_mark) # Sets overallmarks variable to coursework add prelim mark overallmarks = coursework + prelim_mark finalgrade, finalpercentage = grade(overallmarks) # Prints a line of 30 '*' to organise the data print ( 30 * "*" ) # Prints the student name from external file print ( "Student:" , student_name) # Prints the students final percentage print ( "Percentage:" , finalpercentage) # Prints the students final grade print ( "Final Grade:" , finalgrade) # Prints a blank line print () # Boilerplate code if __name__ = = '__main__' : main() |
Output:errorinal Grade: No Award
******************************
Student: Shahida Choudry
Percentage: 70.0
Final Grade: A
******************************
Student: Ian Li
Percentage: 50.0
Final Grade: C
******************************
Student: Petra Carter
Percentage: 39.33333333333333
Final Grade: No Award
Error:Traceback (most recent call last):
File "C:\Users\~XPS~\Desktop\student_grades.py", line 66, in <module>
main()
File "C:\Users\~XPS~\Desktop\student_grades.py", line 51, in main
finalgrade, finalpercentage = grade(overallmarks)
File "C:\Users\~XPS~\Desktop\student_grades.py", line 24, in grade
return grade, percentage
UnboundLocalError: local variable 'grade' referenced before assignment