2016-12-21 100 views
-1

我正在嘗試製作一個計算用戶輸入年級的成績平均值的計算程序,然後將輸入與字典進行比較。這是我的代碼,我相信什麼是錯的。python dictonary和if語句

def average(g1): 
    dic = {"a": [4.],"A": [4.],"A-": [3.66],"a-": [3.66],"B+":[3.33], "b+": [3.33],"B": [3.],"b": [3.],"B-": [2.66], "b": [2.66],"C+": [2.33],"c+": [2.33],"C": [2.],"c": [2.], "D+": [1.66],"d+": [1.66],"D": [1.33],"d": [1.33],"D-": [1.], "d-": [1.],"F": [.66]} 

    for key in dic.keys(): 
     if g1 in dic.keys: 
      print ("hello") 
g1 = raw_input("Please enter grade 1: ") 
average(g1) 
+0

是什麼讓你覺得有什麼不對?當你運行它會發生什麼?它與你的預期有什麼不同? – skrrgwasme

+0

'對於dic.keys()中的關鍵字:'你認爲這樣做了什麼? 'dic.keys'你認爲這有什麼用? – njzk2

回答

0

dic.keys()返回字典中所有鍵的列表。你不需要用for循環遍歷所有的鍵。這應該做你想做的。

def average(g1): 
    dic = {"a": [4.],"A": [4.],"A-": [3.66],"a-": [3.66],"B+":[3.33], "b+": [3.33],"B": [3.],"b": [3.],"B-": [2.66], "b": [2.66],"C+": [2.33],"c+": [2.33],"C": [2.],"c": [2.], "D+": [1.66],"d+": [1.66],"D": [1.33],"d": [1.33],"D-": [1.], "d-": [1.],"F": [.66]} 

    if g1 in dic.keys(): 
     print('hello') 

g1 = input("Please enter grade 1: ") 
average(g1) 
+0

只是要挑剔(因爲這個問題是用Python 3標記的):'dict.keys'不會在Python 3中返回一個列表,而是一個類型爲'dict_keys'的迭代器。 – DeepSpace

1

您可能希望使用由用戶輸入的字母等級相關聯的GPA值:

def average(g1): 
dic = {"A": [4.], "A-": [3.66], "B+":[3.33], "B": [3.], "B-": [2.66], "C+": [2.33], "C": [2.], "D+": [1.66], "D": [1.33], "D-": [1.], "F": [.66]} 

for key in dic.keys(): 
    if g1 == key: 
     print("GPA for '{g1}' = {value}".format(g1=g1, value=dic[key][0])) 
     print ("hello") 
g1 = raw_input("Please enter grade 1: ") 
average(g1.upper()) 

輸出樣本:

Please enter grade 1: a- 
GPA for 'A-' = 3.66 
hello 

我簡化你的字典只用大寫您可以將用戶輸入的字母等級轉換爲大寫字母str.upper()