这是我的代码:
# 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(): 函数。无论如何,我将不胜感激有关如何修复此错误的任何帮助。另外,这是我成功完成程序时正在寻找的结果:点击这里 https://i.stack.imgur.com/zgHOU.png
我希望完成如图所示的平均值,但此时我并不担心它们,只担心来自光传感器的值列表。我不需要达到这些确切的数字,模拟器中的数字会有所不同。