Search code examples
pythonturtle-graphicspython-turtle

Trouble with storing a position in a variable in turtle (python)


Code

import turtle
window = turtle.Screen()
pen = turtle.Turtle()
def reset(p):
    pen.up()
    pen.goto(p);
    pen.forward(30);
    pen.down();
    pen.forward(100);
def cdraw():
   p = pen.position();
   for x in range(180):
      pen.backward(1)
      pen.right(1)
  return p;
  reset

My reset function seems to not be working, I think the problem is with my goto(p) line. I am not sure if I am allowed to use:

 p = pen.position();

My code currently runs cdraw function and then stops.


Solution

  • Your last question involved parentheses that should not have been included:

    turtle.onscreenclick(star()) -> turtle.onscreenclick(star)
    

    This one is the reverse, missing parentheses that are needed:

    reset -> reset()
    

    But there are other problems -- parentheses or not, any code directly following a return statement will never be reached:

    return p;
    reset  # never reached
    

    The snippet of code you provide never calls cdraw() so reset() will never be called. Finally, semicolons really don't have a place in a properly written Python program.

    Below is my best guess at what your program was intended to look like, but there's not enough information to know for sure:

    import turtle
    
    def reset(p):
        pen.up()
        pen.goto(p)
        pen.forward(30)
        pen.down()
        pen.forward(100)
    
    def cdraw():
        p = pen.position()
        for x in range(180):
            pen.backward(1)
            pen.right(1)
        reset(p)
    
    window = turtle.Screen()
    
    pen = turtle.Turtle()
    
    cdraw()
    
    window.exitonclick()
    

    These questions are not about turtle graphics but instead about basic Python programming.