Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loops in Python: not expecting this output

I am not getting why this is returning only one value as I am looping through a list.

def calculateGrade(students_marks):
    # Write your code here
    
    students_avg = []
    for j in students_marks:
        sume = 0
        for i in j:
            sume = sume+ i
        avg = sume/(len(j))
        students_avg.append(avg)
    print(students_avg)

    grade = []
    for item in students_avg:
        if item >= 90:
            grade.append('A+')
        elif 80<item<=90 :
            grade.append('A')
        elif 70<item<=80 :
            grade.append('B')
        elif 60<item<=70 :
            grade.append('C')
        elif 50<item<=60:
            grade.append('D')
        elif item < 50 :
            grade.append('F')
    print(grade)
        

I have tried with 2 elements in the list with [50.6,48] which only returns F.

This is the code I am trying to execute. I am getting the students_avg as the correct output. But when i pass that list through the 2nd for loop i am getting only single output

row 1 = [66, 61, 88, 26, 13] -- for student 1 row 2 = [52, 38, 7, 74, 62] -- for student 2

so we form a list of averages of students and pass that to get the grade . That's the problem .

like image 732
ChaitanyaSai Avatar asked Jan 20 '26 22:01

ChaitanyaSai


1 Answers

You need to indent your code. But also, you are creating an empty array every time it runs the loop. Do it like this:

grade = []
for item in students_avg:
    if item >= 90:
        grade.append('A+')
    elif item in range(80,90):
        grade.append('A')
    elif item in range(70,80):
        grade.append('B')
    elif item in range(60,70):
        grade.append('C')
    elif item in range(50,60):
        grade.append('D')
    elif item < 50 :
        grade.append('F')
print(grade)
like image 127
Mathias Avatar answered Jan 23 '26 13:01

Mathias