Reputation: 107
I wonder if you could help me with this practical exercise:
Make a Program that asks for the 2 grades of 2 students, calculate and store the average of each student in a list, print the number of students with an average greater than or equal to 7.0.
I managed to do it using the for loop, but I would like to use the while loop. I'm trying this code, but the list of averages is not coming out correctly. I appreciate any help.
notesStudents = []
listNotes = []
student = 1
notes = 1
average = 0
while student <= 2:
while notes <= 2:
notesStudents.append(float(input(f"What is the {notes}ª grade of the Student {student}?")))
notes += 1
notes = 1
student += 1
average += notesStudents[notes]
average = average / 3
listNotes.append(average)
print(listNotes)
Upvotes: 0
Views: 79
Reputation: 82939
The notes
and studentNotes
variables should be re-initialized within the loop, otherwise you just keep appending to the same list of studentNotes
. Also, right now you just set average
to the studentNodes[1] / 3
, which is not correct. You should get the sum of all the notes and divide them by the proper number.
listNotes = []
student = 1
while student <= 2:
notes = 1
notesStudents = []
while notes <= 2:
notesStudents.append(float(input(f"What is the {notes}ª grade of the Student {student}?")))
notes += 1
average = sum(notesStudents) / len(notesStudents)
listNotes.append(average)
student += 1
print(listNotes)
This would however be much simpler and less verbose with for
loops and maybe even a list comprehension:
listNotes = []
for student in range(1, 3):
notesStudents = [float(input(f"What is the {n}ª grade of the Student {student}? "))
for n in range(1, 3)]
average = sum(notesStudents) / len(notesStudents)
listNotes.append(average)
print(listNotes)
Upvotes: 0