Reputation: 47
Im working on a program in which I need to plot the movement of a turtle on a plane starting at (100,100) and facing right. In three steps the user can either walk and input how far they wish to go, or turn, where they would change directions in 90 degrees. I have written my function which takes in the original coordinates, manipulates them and returns new coordinates, but my program refuses to accept this. My program returns a manipulated value of my plot variable (renamed coor) , but python doesn't acknlowedge it when I attempt to call it.
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
Upvotes: 1
Views: 60
Reputation: 5252
coor
is only defined within your function, so you can't access it directly from outside of the function without making it global, or by returning the value (as you are) and assigning it to a variable (which you aren't).
When you call the function, do it like so:
coords = movement('turn',coor,i)
Then you will be able see the current value when you try to print it using:
print coords
Upvotes: 0
Reputation: 967
You need to assign the value movement returns in the main body.
The variables you create in a function are destroyed once you exit the function.
Do
coor=movement(inputs...)
instead of
movement(inputs...)
Upvotes: 1