Python,IndexError:列表赋值超出范围(g [ng] floatinput(":"))。我该如何解决?

时间:2017-09-24 02:10:21

标签: python for-loop indexing while-loop

我是编程新手,我目前的课程作业要求我们输入学生人数,输入每个学生的成绩(-1到停止),然后显示成绩报告。我的问题是这个错误消息... IndexError:列表赋值超出范围(g [ng] floatinput(":"))。我该如何解决? 如果还有其他方法可以解决这个问题,我愿意接受建议!

#Input number of students
s=int(input("How many Students are there?: "))
print("=================================================================")

#create list of student grades
for n in range(s):
    g=[0]
    t=0
    ng=0
    ns=0

    print("Enter Student # ",n+1," scores (-1 to stop enter scores):")

#Input grades 
    while g!=-1:
        ng+=1
        print('Grade#', ng, end='')
        g[ng]=float(input(": "))
        ng+=1
    print("=================================================================")
    print("Student #",n+1,"Grade Report")

#Index and recall grades
    for r in g:
        print('Grade#',r+1,':\t',r,end='') 
        if r<60:
            print("\tF")
        elif 60<=r<70:
            print("\tD")
        elif 70<=r<80:
            print("\tC")
        elif 80<=r<90:
            print("\tB")
        elif 90<=r<100 or r>100:
            print("\tA")

#Print average for grades          
    print() 
    if 0<=(t/(ng-1))<60:
        print("Average: ", format(t/(ng-1)), "Your grade so far is F")
    elif 60<=(t/(ng-1))<70:
        print("Average: ", format(t/(ng-1)), "Your grade so far is D")
    elif 70<=(t/(ng-1))<80:
        print("Average: ", format(t/(ng-1)), "Your grade so far is C")
    elif 80<=(t/(ng-1))<90:
        print("Average: ", format(t/(ng-1)), "Your grade so far is B")
    elif 90<=(t/(ng-1))<=100 or (t/(ng-1))>100:
        print("Average: ", format(t/(ng-1)), "Your grade so far is A")
    print("=================================================================")
print("=================================================================")
print("Grade report for your class done!")

1 个答案:

答案 0 :(得分:0)

我现在是一名学生,我完全理解一开始有多么令人沮丧的循环。要回答您的问题,我相信您的部分问题会追溯到您的输入等级循环:

while g!=-1:
    ng+=1
    print('Grade#', ng, end='')
    g[ng]=float(input(": "))
    ng+=1
print("=================================================================")
print("Student #",n+1,"Grade Report")

您正在增加两次。请注意,您有两行ng + = 1。这意味着您的列表中途,您将引用一个不存在的索引,因为您将ng加倍(ng = 2,4,6,8 ...)而不是将其增加1(ng = 1) ,2,3,4)你可能想要的。