"""
calcGPA
@author: nick young
"""
# GPA Calculator. Weights letter grade and credit hours and divides to return final GPA value
def calcGPA():
error=('Improper Input, asshole. GPA is -1.') #Snarky error message
i=0 #tally numbers to count from
a=0
x=0
y=0
list1=list(input("Enter your letter grades earned on an A-F scale:"))
list2=list(input('Enter the credit hours earned for each course in the same order as your first input \nNo spaces:'))
list3=[] #empty list to append weighted values to
if len(list1)!=len(list2) or len(list1)+len(list2)<=0: #verifies lists are same length and not empty
print(error)
elif list1[i].upper() not in ['A','B','C','D','F']:
print(error)
i=i+1
elif list2[a].isdigit()==False:
a=a+1
print(error)
for letter in list1: #loop determines letter grade and returns numeric value per element in list1
if letter.upper=='A': #runs through until each element in list1 has been converted into a numeric value to be weighted
list3.append(4*list2[x])
x=x+1
elif letter.upper=='B':
list3.append(3*list2[x])
x=x+1
elif letter.upper=='C':
list3.append(2*list2[x])
x=x+1
elif letter.upper=='D':
list3.append(1*list2[x])
x=x+1
elif letter.upper=='F':
list3.append(0)
x=x+1
y=0
while y<=len(list1): #loop gathers the collective weight of each class to be divided
weight=float(0)
weight=float(list3[y]*list2[y])
y=y+1
gpa=float(weight/sum(list2))
print(gpa)
calcGPA()
對於此GPA計算器,我需要移動通過和在兩個列表乘匹配元素(列表2 [0] *項目list3 [0] ...)爲長度無論輸入是什麼。代碼已經檢查以確認所有內容都具有相同的長度。運行時,出現錯誤「列表索引超出範圍」。意外錯誤「列表索引超出範圍」
一些谷歌搜索後,我聽到這是因爲當一個變量超出了它應該的範圍,但從我看到的'y'不應該超出list1的長度(這也將是列表2的長度和三)。我試過在while語句中只使用'<'。
附註:我已經知道這個程序可能沒有完全格式化,但我只在我班的第7周。
其他邊注:我使用的Spyder 3 IDE爲我的編譯器
再次查看堆棧跟蹤。它會告訴你哪一行代碼會導致錯誤。 – DyZ
忘了在我的文章中包含這個!它專門用於 weight = float(list3 [y] * list2 [y]) –
作爲一個方面說明,不在...中的list1 [i] .upper()僅檢查_first_等級是否無效,而'list2 [a] .isdigit()== False'也只檢查第一個數字。可能不是你想要的。 – DyZ