Question

grade=[]
names=[]
highest=0


#taking number of calues

cases=int(input('Enter number of cases: '))
for case in range(1,cases+1):
    print('case',case)

    #taking number of students

    number=int(input('Enter number of students: '))
    for numbers in range (1,number+1):

        #getting name and marks
        name=str(input('Enter name of student: '))
        names.append(name)
        mark=float(input('Enter mark of student:'))
        grade.append(mark)


    print('Case',case,'result') 

    #printing the results!
    average=float(sum(grade)/number)
    print('Average is: %.2f '%(average))
    print('Highest Score is: %.2f'%(max(grade)))
    print('Student with highest score: ',names[grade.index(max(grade))])

output->Enter number of cases: 2
case 1
Enter number of students: 2
Enter name of student: josh
Enter mark of student:98
Enter name of student: sarah
Enter mark of student:87
Case 1 result
Average is: 92.50 
Highest Score is: 98.00
Student with highest score:  josh
case 2
Enter number of students: 3
Enter name of student: shania
Enter mark of student:78
Enter name of student: arleen
Enter mark of student:89
Enter name of student: zoya
Enter mark of student:89
Case 2 result
Average is: 147.00 
Highest Score is: 98.00
Student with highest score:  josh

MY avg. in 3 cases is screwed up also it doesn't show the highest!. I was wondering how can i get the highest if there are 2 same occurrences. Highest will be only the first occurrence. DO you guys get what i mean?

Was it helpful?

Solution

The problem is that in the second iteration through the case loop, you are are also looking at the names and grades from the previous loop because you never emptied the lists. You need to empty the lists at the beginning of the loop. Create the empty lists at the top of the loop:

for case in range(1,cases+1):
    print('case',case)
    grade=[]
    names=[]
    highest=0

You can (and should) do this instead of defining the variables at the top of the file.


To see what was going wrong (before adding my fix), do this:

average=float(sum(grade)/number)
print(grade)
print(names)
print('Average is: %.2f '%(average))
print('Highest Score is: %.2f'%(max(grade)))
print('Student with highest score: ',names[grade.index(max(grade))])

You will see that the lists have the values from the previous iteration through the loop.

OTHER TIPS

Basically, the problem is that the list is filled at the beginning of the loop itself, attempt clearing the list before the loop iteration. Inorder to do so:

for case in range(1,cases+1):
     print(`case`,case)
     grade=[]
     names=[]
     highest=0

The second iteration through the case loop makes a problem here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top