list index out of range - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: list index out of range (/thread-6185.html) |
list index out of range - DrPengin - Nov-09-2017 I am in the second half term of the first year of a GCSE Python course. For a piece of Homework, I need to write a program that converts marks to grades based on given grade boundaries, then store them in a list to print out the number and percentage of passes and fails, with grade "C" or better being a pass. here is what I have written: def Grade(Mark): if 0 <= Mark <= 39: Grade = "U" elif 40 <= Mark <= 49: Grade = "E" elif 50 <= Mark <= 59: Grade = "D" elif 60 <= Mark <= 69: Grade = "C" elif 70 <= Mark <= 79: Grade = "B" elif 80 <= Mark <= 89: Grade = "A" elif 90 <= Mark <= 100: Grade = "A*" return Grade def FailPass(Count): NumPass = 0 NumFail = 0 for Loop in range(Count+1): if Grades[Count] not in("C","B","A","A*"): NumFail += 1 else: NumPass += 1 PerPass = (NumPass/Count)*100 ParFail = (NumFail/Count)*100 return [PerPass,PerFail,NumPass,NumFail] Grades = [] Counter = 0 Input = 1 while Input != 0: Input = int(input("\nWelcome!\n\ Press '1' to convert a mark into a grade\n\ Press '2' to display the amount and percentage of passes\n\ Press '3' to display the amount and percentage of fails\n\ Press '0' to quit\n\ >>> ")) if Input == 1: MarkIn = int(input("\nPlease enter the mark you wish to convert\n\ >>> ")) if 0 <= MarkIn <= 100: GradeOut = Grade(MarkIn) print("\nA mark of",MarkIn,"is equivalent to a grade",GradeOut,) Grades.append(GradeOut) Counter += 1 else: print("\nPlease enter a valid mark.") elif Input == 2 or Input == 3: FP = FailPass(Counter) if Input == 2: print("\nThere were",FP[3],"passes, which means %"+str(FP[1]),"of all students passed.") else: print("\nThere were",FP[4],"fails, which means %"+str(FP[2]),"of all students failed.")but I get the error 'list index out of range' in line 22. I don't know what I am doing wrong. Also any other tips would be appreciated. RE: list index out of range - gruntfutuk - Nov-09-2017 Good try. It is not usual in python to have a capital at the start of a variable name. I've only had a quick look through your code, but I can't see where you've initialised your grade list (the results) in order to do any analysis on it, thus you are attempting to loop through an empty list. You need a line to set some test data for now. Incidentally, with your menu, why bother converting to integer, just test for "0", "1", etc. The while loop can be simpler: while True: and do a break if not input: (as an non-null string is True.The part of your code outside of functions is a little hard to read. Might be worth moving code into more functions so that it is easier to follow the flow/logic. |