2017-02-04 141 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。