I am new to coding and following the topics in Python course here at Codecademy. I am currently studying the loops and thought I’d take my time outside the course to practice them a little before I go on further in the course. I have written the code below but cannot figure out why a certain part of it is not working. I’d appreciate it if someone points me in the right direction.
I have a list of grades stored in the variable
grades. There are 10 grades in this variable. I am trying to print the grades that are above the average of the grades in the list. Once the average is calculated, it is stored in a variable called
average and the average is 48.5. To make sure the calculations are correct, I have printed them at the bottom of the code and calculated them manually as well. But when it comes to printing the grades above the average, I cannot get the
if statement to work. It is taking out some of the numbers like 12 and 24 like it should, but still keeping other grades lower than average like 24, 28 and 47.
Here is the code:
grades = [62, 75, 33, 24, 28, 56, 88, 12, 47, 60] sum_grades = 0 for grade in grades: sum_grades += grade length = len(grades) average = sum_grades / length if grade > average: print(grade) print("The total is " + str(sum_grades) + ".") print("The average is " + str(average) + ".") print("The list has " + str(len(grades)) + " numbers.")
And here is the result:
62 75 33 24 28 56 88 47 60 The total is 485. The average is 48.5. The list has 10 numbers.
I am not sure if I am doing something that shouldn’t be done in a loop or if this is related to something I haven’t learned yet. I tried searching for a possible solution on Google but couldn’t find anything useful.
Thanks in advance for the help! If you notice something in the code that is not considered best practice, please feel free to point them out.