[Tutor] function error

ALAN GAULD alan.gauld at btinternet.com
Sat Oct 2 22:34:52 CEST 2010





> ##############################################################################
> import  turtle, random
> 
> def checkForward(distance):
>      old_position = turtle.position()
>      turtle._pen.up()
>      turtle.forward(distance)
>     forward_failed =  outOfBounds()

you set forward failed but never use it?

>     turtle.setx(old_position[0]);  turtle.sety(old_position[1])
>      turtle._pen.down()
>     if outOfBounds() ==  'false':
>          turtle.forward(distance)

If you change outOfVBounds to return a real boolean result you can just say

if outOfBounds():
   etc...

> def  stuck():
>     return forward_failed

forward failed does not exist here it is a local variable in checkForward.
If you want to use it like this you need to create it as a global 
variable outside any of the function bodies.


> def  outOfBounds():
>     if (abs(turtle.position()[0]) >  turtle.window_height()/2) or
> (abs(turtle.position()[1]) >  turtle.window_width()/2):
>         return  "true"
>     else:
>          return "false"

You can miss the if statement and just return the expression, 
that will give you a real True/False boolean result which is 
easier to work with than strings.

return (abs(turtle.position()[0]) >  turtle.window_height()/2) or
         (abs(turtle.position()[1]) >  turtle.window_width()/2)

However does this test check for out of bounds in all directions?
What happens if the turtle is travelling west/south rather than 
east/north? It may work but I don't see it.

> def randomMove2(d1, d2, a1,  a2):
>      while 1:

This is usually written as while True: nowadays

>           turtle.left(random.uniform(a1,a2))
>           checkForward(random.uniform(d1,d2))
>          if  outOfBounds() == 'true':
>                turtle.right(180)

I don;t know iof any of that solves the probnl;em but it 
might tidy the code a little

HTH,

Alan G.


More information about the Tutor mailing list