2017-02-23 50 views
0
""" 
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爲我的編譯器

+0

再次查看堆棧跟蹤。它會告訴你哪一行代碼會導致錯誤。 – DyZ

+0

忘了在我的文章中包含這個!它專門用於 weight = float(list3 [y] * list2 [y]) –

+0

作爲一個方面說明,不在...中的list1 [i] .upper()僅檢查_first_等級是否無效,而'list2 [a] .isdigit()== False'也只檢查第一個數字。可能不是你想要的。 – DyZ

回答

1

最初的問題是,你已經使用了方法財產來代替。你需要這個:

for letter in list1: 
    if letter.upper()=='A': 
     list3.append(4*list2[x]) 

然後你會遇到問題,list2是一個字符列表,而不是整數。試試這個:

 list3.append(4*int(list2[x])) 

那些應該讓你在接下來的幾個隆起。

+0

修復了不少問題!但是,仍然返回相同的'IndexError:列表索引超出範圍'消息的行'weight = float(list3 [y] * list2 [y])' –

+0

我懷疑問題是你仍然有** y <= len(list2)**作爲您的循環控制。你需要** y Prune

+0

是的,你在這段代碼中有多個問題。 y在這一點上的價值是什麼?你死前多少次通過循環?它操作的是什麼值:是否將所有數字(字符串)正確轉換爲整數? 如果您有其他問題,我們需要您發佈一個新問題。如果您遇到同樣的問題,我們需要您更新此問題以反映您的代碼的當前狀態。 – Prune

1
while y<len(list1): 

代替

while y<=len(list1): 

索引是從零開始的大多數語言,所以這是你平時想做的事情。

+0

我發佈的代碼中包含'='。在我進行故障排除時,我沒有做過測試,只是爲了確保這不是問題。 –