python - 需要帮助返回在函数外部使用的变量 (Python)

标签 python function return call

我正在开发一个程序,在该程序中我需要绘制乌龟在从 (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

最佳答案

需要在主体中赋值移动返回值。

一旦退出函数,您在函数中创建的变量就会被销毁。

coor=movement(inputs...)

而不是

movement(inputs...)

关于python - 需要帮助返回在函数外部使用的变量 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35744007/

相关文章:

python - 仅当模式不在转义字符串内时,re.match才返回匹配对象

python - 尝试...否则...除了语法错误

c# - 如何有效地计算对数返回

python - 每个 Django 应用程序的不同 virtualenv

python - 从字符串和列表的元组中以字符串形式返回所有值

C++ 模板类

php - 为什么输出不显示新变量?

c++ - 在 C++ 函数中通过引用传递

java - 如何将与 editText 有关的字符串值返回到另一个类

javascript - Javascript : Nested Return Statement, return inside Return