[英]Need help returning a variable for use outside a function (Python)
我正在開發一個程序,需要在這個程序中繪制烏龜在(100,100)開始並面向右的平面上的運動。 通過三個步驟,用戶可以步行並輸入他們想走多遠的位置,也可以轉彎他們將以90度改變方向的位置。 我編寫了接受原始坐標,對其進行操作並返回新坐標的函數,但是我的程序拒絕接受這一點。 我的程序返回了我的plot變量的操作值(重命名為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...)
coor
僅在函數內定義,因此您不能在不使其全局化的情況下直接從函數外部訪問它,也不能通過返回值(如您所願)並將其分配給變量(不是)來訪問它。
調用該函數時,請按照以下方式進行操作:
coords = movement('turn',coor,i)
然后,當您嘗試使用以下命令打印當前值時,您將能夠看到它:
print coords
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.