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
我的平均值在3个案例被搞砸了它也没有显示最高!我想知道如果有两个相同的事件,我怎么能得到最高。最高只会是第一次出现。你们明白我的意思吗?
答案 0 :(得分:2)
问题在于,在通过case
循环的第二次迭代中,您还要查看前一循环中的名称和等级,因为您从未清空过列表。您需要在循环开始时清空列表。在循环顶部创建空列表:
for case in range(1,cases+1):
print('case',case)
grade=[]
names=[]
highest=0
您可以(并且应该)执行而不是来定义文件顶部的变量。
要查看出现了什么问题(在添加修复程序之前),请执行以下操作:
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))])
您将看到列表中包含上一次迭代到循环的值。
答案 1 :(得分:0)
基本上,问题是列表在循环开始时填充,尝试在循环迭代之前清除列表。为此:
for case in range(1,cases+1):
print(`case`,case)
grade=[]
names=[]
highest=0
case
循环的第二次迭代在这里产生问题