2017-02-25 89 views
-1
#Author: Zian Lin 
#Date: March 22th 2016 
#Purpose: Calculating your GPA. 

#Variables 
grades = [] 
finalgpa = [] 
number = 1 
rank = 0 
counter = 0 
boolean = 0 
lower = [0, 60, 64, 67, 70, 74, 77, 80, 84, 87, 90, 94] 
upper = [59, 63, 66, 69, 73, 76, 79, 83, 86, 89, 93, 100] 
gpa = [0, 0.7, 1, 1.3, 1.7, 2.0, 2.3, 2.7, 3, 3.3, 3.7, 4] 

start = str(input("Do you want to calculate your GPA?")) 

#Collects all the grades 
if start == "Yes" or "yes": 
    while number <= 7: 
    answer = input("What is your grade for class " + str(number) + "?") 
    if int(answer) > 100 or int(answer) < 0: 
     print("Please input a valid number.") 
    else: 
     grades.append(answer) 
     number = number + 1 

#Displays grades 
print("These the grades you've inputted.") 
print(str(grades[:])) 

#Convert grades to GPA 
if counter != 7: 
    if int(grades[counter]) >= int(lower[rank]) and int(grades[counter]) <= int(upper[rank]): 
    #Scroll through 
    finalgpa.append(gpa[counter]) 
    counter = counter + 1 
    boolean = 1 
    if boolean == 0: 
    rank = rank + 1 

#Average all the GPAs 
def averager(a, b, c, d, e, f, g): 
    return (a+b+c+d+e+f+g)/7 

#Print final GPA 
result = averager(finalgpa[0], finalgpa[1], finalgpa[2], finalgpa[3], finalgpa[4], finalgpa[5], finalgpa[6]) 
print("Your GPA is " + str(result) + "!") 

對於我的電腦課,我不得不在Python中做些什麼,所以我決定做一個GPA計算器。上述#PRINT最終GPA理論上一切工作正常,但是當我嘗試以平均最終GPA,它給了我這個錯誤:GPA計算器只給答案1.29?

回溯(最近通話最後一個): 文件「蟒蛇」,第47行,在 IndexError :列表索引超出範圍

這是怎麼回事?

+0

'finalgp' a未完全填充,只有'grades'長度爲7 –

回答

0

您的if counter != 7塊是錯誤的。

  1. 首先,你要遍歷每個年級
  2. 你也想遍歷每個等級
  3. finalgpa.append(gpa[counter])是錯誤的。你想gpa[rank]沒有反擊,因爲計數器是該指數爲等級不GPA,

這裏是修復:

#Convert grades to GPA 
for grade in grades: 
    for rank in range(0, len(gpa)): 
    if grade >= int(lower[rank]) and grade <= int(upper[rank]): 
     finalgpa.append(gpa[rank]) 
     break 

更簡單的方式來做到平均將採取一個數組中,說finalgpa,然後sum(finalgpa)/len(gpa)