Home > Mobile >  Loops in Python: not expecting this output
Loops in Python: not expecting this output

Time:09-27

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 .

CodePudding user response:

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)

CodePudding user response:

you are creating empty grade list everytime you go thru the students_avg, that's why you are getting only one result.

Just do it like:

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')
    return grade


print(calculateGrade([[90,89.9], [90,90]]))

Prints:
# [89.95, 90.0]
# ['A', 'A ']

Or a little more elegant solution

rating = {
    'A ': [90, 100],
    'A': [80, 90],
    'B': [70, 80],
    'C': [60, 70],
    'D': [50, 60],
    'F': [0, 50]}


def calculate_averages(
        students_marks
):
    students_avg = [sum(student) / len(student) for student in students_marks]
    return students_avg


def get_grade(
        averages
):
    grades = []
    for item in averages:
        for k, v in rating.items():
            if v[0] <= item < v[1]:
                grades.append(k)
    return grades


if __name__ == "__main__":
    points = [[90, 89.9], [90, 90]]
    print(get_grade(calculate_averages(points))) # Prints ['A', 'A ']


CodePudding user response:

Your grade is float you can't use range like below:

>>> 50.6 in range(50,60)
False

If you want to use your code you can use round() like below:

>>> round(50.6) in range(50,60)
True

or you can try this:

dct_rng = {'A ':[90,100], 'A':[80,90], 'B' :[70,80], 
           'C':[60,70], 'D':[50,60], 'F':[0,50]}

grade = []
students_avg = [50.6 ,48]

for item in students_avg:
    for k,v in dct_rng.items():
        if v[0] < item <= v[1]:
            grade.append(k)

Output:

['D', 'F']

CodePudding user response:

Your code needs indentation and if you have defined item less than 50 outside your for loop, so it is executing the last conditional.

If your code is indeed indented properly and you have made a mistake in pasting your code here, even then your list grade needs to be defined outside the loop, because it gets reassigned to grade = [] for every iteration, and whatever value it had in its previous iteration is gone.

Also, you require non integral values, range() will produce integers in the range, so for range(m,n) will have integers : m , m 1,... n-1

So any float, for ex: m.x will not be generated in range(m,n), for that comparison, it is better to have > and <. Also using range() is unoptimal because of the extra space it will take.


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

print (grade)
  • Related