2014-02-23 244 views
2

我一直得到這個GPA計算器的錯誤,該計算器應該根據4個等級來計算您的GPA。此外,只要輸入了一封未命名爲A,B,C,D,F的信件,我就不知道該怎麼辦了,該程序需要終止。GPA Calc Python

def GetName(): 
    name = raw_input ("Enter the student's name ") 
    grade1 = raw_input ("Enter a grade: ") 
    grade2 = raw_input ("Enter a grade: ") 
    grade3 = raw_input ("Enter a grade: ") 
    grade4 = raw_input ("Enter a grade: ") 
    return name, grade1, grade2, grade3, grade4 

def GetGrades(grade1, grade2, grade3, grade4): 
     if [grade1, grade2, grade3, grade4] == 'A' or [grade1, grade2, grade3, grade4] == 'a': 
       [g1, g2, g3, g4] =4 
     elif [grade1, grade2, grade3, grade4] == 'B' or [grade1, grade2, grade3, grade4] == 'b': 
       [g1, g2, g3, g4] =3 
     elif [grade1, grade2, grade3, grade4] == 'C' or [grade1, grade2, grade3, grade4] == 'd': 
       [g1, g2, g3, g4] =2 
     elif [grade1, grade2, grade3, grade4] == 'D' or [grade1, grade2, grade3, grade4] == 'd': 
       [g1, g2, g3, g4] =1 
     elif [grade1, grade2, grade3, grade4] == 'F' or [grade1, grade2, grade3, grade4] == 'f': 
       [g1, g2, g3, g4] =0 
     else: 
       return 'invalid grade' 
     return g1, g2, g3, g4 

def CalcGPA(g1,g2,g3,g4): 
    GPA = (g1,g2,g3,g4)/4 
    return GPA 


def main(name, GPA): 
    print "The GPA for", name,"is",GPA 
    return 0 

GetName()=name,grade1,grade2,grade3,grade4 
GetGrades(grade1,grade2,grade3,grade4)=g1,g2,g3,g4 
CalcGPA(g1,g2,g3,g4)=GPA 
main(name,GPA)=0 
+0

究竟發生了什麼?向我們顯示完整的錯誤消息。 – user2357112

+0

我嘗試運行該程序,它說:「你的程序中有一個錯誤:***不能分配給函數調用線34 – user3317056

回答

1

分配在Python分配上等號的左邊參考的右手邊的值,所以你需要解壓的元組在左邊。

def GetName(): 
    name = raw_input("Enter the student's name ") 
    grade1 = raw_input("Enter a grade: ") 
    grade2 = raw_input("Enter a grade: ") 
    grade3 = raw_input("Enter a grade: ") 
    grade4 = raw_input("Enter a grade: ") 
    return name, grade1, grade2, grade3, grade4 

grademap = { 'A': 4, 'B': 3, 'C': 2, 'D': 1 } 

def grade2int(x): 
    try: 
     return grademap[x.upper()] 
    except KeyError: 
     raise Exception('invalid grade: ' + x) 

def GetGrades(grades): 
    return map(grade2int, grades) 

def CalcGPA(grades): 
    return sum(grades)/len(grades) 

def main(name, GPA): 
    print "The GPA for", name, "is", GPA 
    return 0 

if __name__ == '__main__': 
    name, grade1, grade2, grade3, grade4 = GetName() 
    grades = GetGrades([grade1, grade2, grade3, grade4]) 
    GPA = CalcGPA(grades) 
    main(name, GPA) 
+0

這運行,但我得到一個錯誤後,我進入我的四個等級,說太多的值解壓 – user3317056

+0

實際上有很多原始問題,我只會發布固定來源,問問我是否有任何問題。 –

0

它看起來像有幾個錯誤,這裏有一些提示。

GetGrades第一名您的名單[grade1,grade2,grade3,grade4]永遠不會等於'A'它只會等於一個列表,所以您將不得不重新考慮如何測試成績。

其次你需要等級值的總和,並且想要除以浮點數或python將刪除小數(除非用小數輸入g1-4)。

def CalcGPA(g1,g2,g3,g4): 
    GPA = sum(g1,g2,g3,g4)/4.0 
    return GPA 

三錯誤是來自你是如何調用該函數的語法來 應該是:

name,grade1,grade2,grade3,grade4= GetName() 
g1,g2,g3,g4=GetGrades(grade1,grade2,grade3,grade4) 
GPA = CalcGPA(g1,g2,g3,g4) 
0=main(name,GPA) 

至於獲取程序輸入無效年級的時候結束,你可以考慮放入一個while循環,當畢業生無效時結束。