的Python:'没有定义

问题描述:

这里是我的代码:的Python:'没有定义

# This program makes the robot calculate the average amount of light in a simulated room 

from myro import * 
init("simulator") 

from random import* 

def pressC(): 
    """ Wait for "c" to be entered from the keyboard in the Python shell """ 
    entry = " " 
    while(entry != "c"): 
     entry = raw_input("Press c to continue. ") 
    print("Thank you. ") 
    print 

def randomPosition(): 
    """ This gets the robot to drive to a random position """ 
    result = randint(1, 2) 
    if(result == 1): 
     forward(random(), random()) 
    if(result == 2): 
     backward(random(), random()) 

def scan(): 
    """ This allows the robot to rotate and print the numbers that each light sensors obtains """ 
    leftLightSeries = [0,0,0,0,0,0] 
    centerLightSeries = [0,0,0,0,0,0] 
    rightLightSeries = [0,0,0,0,0,0] 
    for index in range(1,6): 
     leftLight = getLight("left") 
     leftLightSeries[index] = leftLightSeries[index] + leftLight 
     centerLight = getLight("center") 
     centerLightSeries[index] = centerLightSeries[index] + centerLight 
     rightLight = getLight("right") 
     rightLightSeries[index] = rightLightSeries[index] + rightLight 
     turnRight(.5,2.739) 
    return leftLightSeries 
    return centerLightSeries 
    return rightLightSeries 

def printResults(): 
    """ This function prints the results of the dice roll simulation.""" 
    print " Average Light Levels " 
    print " L  C  R " 
    print "=========================" 
    for index in range(1, 6): 
     print str(index) + " " + str(leftLightSeries[index]) + " " + str(centerLightSeries[index]) + " " + str(rightLightSeries[index]) 

def main(): 
    senses() 
    pressC() 
    randomPosition() 
    scan() 
    printResults() 

main() 

所以,我当我运行我的程序收到此错误。

NameError: global name 'leftLightSeries' is not defined 

我知道我必须做一些与return语句有关的错误。我不确定是否只能在用户定义的函数结束时返回一个变量。如果这是真的,那么我应该分开scan():函数。无论如何,我将不胜感激任何帮助如何解决这个错误。此外,这是我期待的,当我成功地完成我的计划结果: Click Here

我找喜欢的图片显示完成的平均值,但我并不担心他们在这一点上,只有来自光传感器的数值列表。我不需要达到那些确切的数字,这些数字在模拟器中会有所不同。

+2

'leftLightSeries'是一个局部变量的'扫描中()'功能,只存在那里。因此它不适用于'printResults()'。和多次连续的'return'调用,这在任何语言中都没有意义。 'return'立即将执行控制权发送回原始调用位置。返回后的任何代码行都不会被执行。 –

+1

您没有使用scan()的返回值。但是,如果您确实想从函数返回三个值,则可以将它们作为元组返回,例如'返回(leftLightSeries,centerLightSeries,rightLightSeries)'。 – MarkU

+1

只有第一个'return'语句会被执行('return leftLightSeries')。如果您想要返回多个值,请使用字典,元组,列表或列表。 – jDo

如果要从scan()返回多个项目,请不要使用三个单独的return语句。相反,这样做:

return leftLightSeries, centerLightSeries, rightLightSeries 

此外,当你调用函数,你必须分配变量(一个或多个)返回的值;它不会自动创建具有相同名称的新本地变量。因此,在main,调用scan()这样的:

leftLightSeries, centerLightSeries, rightLightSeries = scan() 
+0

由于某种原因,我仍然在收到名称错误 –