2013-12-13 118 views
1

我正在嘗試在Python中製作一個腳本,它將結合西班牙語動詞。這是我第一次使用Python編寫腳本,所以這可能是一個簡單的錯誤。當我運行該腳本,我輸入 「喲特納」,並收到一個錯誤:NameError:名稱''未定義

Traceback (most recent call last): File "", line 13, in File "", line 1, in NameError: name 'yo' is not defined

  • 多見於:http://pythonfiddle.com/#sthash.bqGWCZsu.dpuf

    # Input pronoun and verb for conjugation. 
    text = raw_input() 
    splitText = text.split(' ') 
    conjugateForm = eval(splitText[0]) 
    infinitiveVerb = eval(splitText[1]) 
    
    # Set the pronouns to item values in the list. 
    yo = 0 
    nosotros = 1 
    tu = 2 
    el = 3 
    ella = 3 
    usted = 3 
    
    # Conjugations of the verbs. 
    tener = ["tengo", "tenemos", "tienes", "tiene", "tienen"] 
    ser = ["soy", "somos", "eres", "es", "son"] 
    estar = ["estoy", "estamos", "estas", "esta", "estan"] 
    
    # List of all of the infinitive verbs being used. Implemented in the following "if" statement. 
    infinitiveVerbs = [tener, ser, estar] 
    
    # Check to make sure the infinitive is in the dictionary, if so conjugate the verb and print. 
    if infinitiveVerb in infinitiveVerbs: 
        print("Your conjugated verb is: " + infinitiveVerb[conjugateForm]) 
    

回答

2

當您使用eval()功能,正在評估它的參數是一個Python語句。我不認爲這是你想要做什麼......

如果你想獲得的代名詞進入conjugateForm變量,而動詞進入infinitiveVerb變量,只需使用:

conjugateForm, infinitiveVerb = text.split() 

默認情況下,split()以空格分隔,因此' '不是必需的。

1

比允許用戶訪問程序的內部結構更好的是將鍵存儲爲字符串。那麼你根本不需要eval

pronouns = { "yo": 0, "nosotros": 1, "tu"; 2, "el": 3, "ella": 3, "usted": 3 } 

,同樣

​​

現在你可以使用用戶的輸入,鍵進入兩個庫。

(我不知道西班牙語是否有單獨的傳統,但常見的安排是先列出單數形式,然後是複數形式,無論是第一,第二和第三人。第二和第三人複數)。

+1

此外,'eval'是一個安全風險。考慮一下,如果用戶輸入'os.system('/ home/hack.sh')'作爲程序的輸入,會發生什麼。 – tripleee