【问题标题】:Need help returning a variable for use outside a function (Python)需要帮助返回一个变量以在函数外部使用(Python)
【发布时间】:2016-06-15 02:47:24
【问题描述】:

我正在开发一个程序,在该程序中,我需要绘制一只乌龟在从 (100,100) 开始并面向右侧的平面上的运动。在三个步骤中,用户可以步行并输入他们想要走多远,或者转身,他们将在 90 度内改变方向。我已经编写了我的函数,它接收原始坐标,操作它们并返回新坐标,但我的程序拒绝接受这个。我的程序返回了我的绘图变量(重命名为 coor)的操作值,但是当我尝试调用它时,python 没有确认它。

   plot= [100,100]
i=0
def movement(step,coor,i):
    x= coor[0]
    y= coor[1]
    if step == 'turn':
        i = i+1
        return coor,i
    else: 
        if i == 0:
            direct= 'right'
        elif i == 1:
            direct= 'down'
        elif i == 2:
            direct= 'left'
        elif i ==3:
            direct= 'up'
        else:
            i = 0
            direct= 'right' 
        if direct == 'right':
            coor= [x-step,y]
            return coor
        elif direct == 'down':
            coor= [x,y+step]
            return coor
        elif direct== 'left':
            coor == [x+step, y]
            return coor
        elif direct == 'up':
            coor == [x, y-step] 
            return coor
step1= raw_input('Step choice (turn or walk) => ')
print step1
step1=step1.lower()
if step1 == 'walk':
    numsteps1= input('Number of steps => ')
    movement(numsteps1,plot,0)
elif step1== 'turn':
    movement('turn',plot,0)
else:
    print 'Illegal step choice.'
step2= raw_input('Step choice (turn or walk) => ')
print step2
step2=step2.lower()
if step2== 'walk':
    numsteps2= input('Number of steps => ')
    movement(numsteps2,coor,i)
if step2=='turn':
    movement('turn',coor,i)
else:
    print 'Illegal step choice.'
step3=raw_input('Step choice (turn or walk) => ')
print step3
step3=step3.lower()
if step3=='walk':
    numsteps3= input('Number of steps => ')
    movement(numsteps3,coor,i)
if step3=='turn':
    movement('turn',coor,i)
else:
    print 'Illegal step choice.'
print coor

【问题讨论】:

  • 不承认什么?您希望看到什么,这与您实际看到的有什么不同?请注意,您可能正在返回一个值,但您似乎没有对该返回值做任何事情。
  • 你能不能把你的错误也贴出来,这样便于理解问题出在哪里

标签: python function return call


【解决方案1】:

coor 仅在您的函数中定义,因此您不能直接从函数外部访问它而不使其成为全局变量,或者通过返回值(如您所愿)并将其分配给变量(您不是)。

当你调用函数时,这样做:

coords = movement('turn',coor,i)

然后,当您尝试使用以下方式打印时,您将能够看到当前值:

print coords

【讨论】:

    【解决方案2】:

    您需要在主体中分配值移动返回。

    您在函数中创建的变量会在您退出函数后被销毁。

    coor=movement(inputs...)
    

    而不是

    movement(inputs...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      相关资源
      最近更新 更多