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