I have a list with students in a course and their grades. I want to check if there are any failing the course (their average being less than 60%).
I want to run a for loop, and if the condition isn’t met by the end of the loop (student’s average is less than 60%), print “No failing students”. However, I want to print all the students that are failing, if there are some. So I need to continue the loop without it breaking when it sees the first failing student.
This is my code. I read online to use the break function with else outside the loop, but like that, the loop stops when it sees the first failing student.
slist = [[“Andrew”, 29, 67, 58], [“Charles”, 98, 76, 85], [“Penny”, 63, 45, 23]]
for students in slist:
total = 0
count = 0
for grade in students[1:len(students)]:
grade = int(grade)
total = grade
count = 1
average = total/count
student = students[0]
if average < 60:
print(f"{student} is failing with {average}%!")
break
else:
print(“No failing students!”)
The output ends up being:
output:
Andrew is failing with 51.333%!
Also, whenever I remove the break statement, it prints all the failing students, and that there are no failing students:
output:
Andrew is failing with 51.333%!
Penny is failing with 43.666%!
No failing students!
I want the output to be:
output:
Andrew is failing with 51.333%!
Penny is failing with 43.666%!
And when the condition isn’t met and no students are failing:
output:
No failing students!
CodePudding user response:
sList = [["Andrew", 29, 67, 58], ["Charles", 98, 76, 85], ["Penny", 63, 45, 23]]
fail = []
for name, *grades in sList:
grade = sum(grades) / 3
if grade < 60:
fail.append([name, grade])
print(f"{name} is failing with {grade:.2f}%!")
if len(fail) == 0:
print('no student is failing')
else:
print(fail)
which will output:
Andrew is failing with 51.34%!
Penny is failing with 43.67%!
[['Andrew', 51.333333333333334], ['Penny', 43.666666666666664]]
and will output:
no student is failing
if no students are failing.
Hopefully this helps and is what you're wanting!
CodePudding user response:
Keeping with what you want your output to be, and with low modification of your code:
slist = [['Andrew', 29, 67, 58], ['Charles', 98, 76, 85], ['Penny', 63, 45, 23]]
flist = []
for students in slist:
total = 0
count = 0
for grade in students[1:len(students)]:
grade = int(grade)
total = grade
count = 1
average = total/count
student = students[0]
if average < 60:
print(f"{student} is failing with {average}%!")
flist.append(students)
if flist == []:
print('No failing students!')