2017-02-04 137 views
0

我剛開始學習OOP並且一直在努力。這個問題可能會讓我立刻面對。「全局名稱未定義」錯誤

def Travel(): 
    choice = str() 
    choice = input("Where will you search?\nChoose F for Front or T for Trunk\n") 
    if choice == "F": 
     LocF() 
    elif choice == "T": 
     LocT(i) 

def LocF(): 
    print("Looking through the front of the car, you find a screwdriver.\nYou figure that might help a bit.") 
    inv = ("screwdriver") 
    return i 

def LocT(i): 
    if i[0] == "screwdriver": 
     print("You use your screwdriver to pop the inside of the trunk door lock off.") 
     time.sleep(0.5) 
     print("You make it to class with seconds to spare.") 
    else: 
     print("You can't get to the trunk yet.") 
     Travel() 
+1

您沒有在'LocF()'中定義我... –

+0

,您創建了一個變量'inv',但嘗試返回一個不存在的變量'i'。改變一個到另一個。 –

回答

0

我會假設你先撥打Travel()函數。

如果調用了Travel(),您現在將輸入一個值爲'F'或'T'的字符串。

如果輸入是'F',LocF()將被調用,LocF()您返回i但您沒有定義它。

如果輸入是'T',將會調用LocT(),並且由於Travel()範圍內沒有i,因此解釋器將在外部尋找i。外面也沒有i,所以這個錯誤是可以理解的。

有幾種方法可以修復你的代碼,但是因爲我不知道你想做什麼,所以我不禁進一步。

而你的問題是關於靜態和動態作用域,而不是OOP。