jeudi 28 février 2019

what's the difference betwwen "if -if -else" and "if-elif-else"

enter link description here

when I typed this code:

def gradingStudents(grades):
    ls = []
    for grade in grades:
        if grade <38:
            new_grade = grade
        else:
            n = grade //10
            t = grade % 10 
            if t <5 and (5-t)<3:
                new_grade = n * 10 + 5

            if t > 5 and (t - 5) >2:
                new_grade = (n+1) * 10
            else:
                new_grade =grade
        ls.append(new_grade)   
    return ls

It's get the wrong answer.But when I changed the second if statement to elif,it's correct.I'm not very clear about what happened:

 def gradingStudents(grades):
    ls = []
    for grade in grades:
        if grade <38:
            new_grade = grade
        else:
            n = grade //10
            t = grade % 10 
            if t <5 and (5-t)<3:
                new_grade = n * 10 + 5

            # I use "elif" replace "if"
            elif t > 5 and (t - 5) >2:
                new_grade = (n+1) * 10
            else:
                new_grade =grade
        ls.append(new_grade)   
    return ls

Aucun commentaire:

Enregistrer un commentaire