Turtle.xcor() is not being applied as my default argument value

So I am messing around with Trinket’s Python code. I wanted to make a quick function where I can set the x, y, or both positions. This is what I have at the moment:

def MoveTo(x = t.xcor(), y = t.ycor()):
  print 'xcor:', t.xcor(), 'ycor:', t.ycor()
  print 'x:', x, 'y:', y
  t.penup()
  t.goto(x, y)
  t.pendown()
  t.seth(0)

What should happen is if I specify the y to be -50 T.MoveTo(y=-50), it should keep its current x position the same, and only change the y position. However, what happens is this:

xcor: -100.0 ycor: 0.0
x: 0.0 y: -50

I’m not quite sure why the -100 for my xcor() is not being applied to the variable x. Instead it defaults to zero

(I’m still new to posting on here, so if the way I am asking my question is wrong, please let me know~)

Answer

It is generally not a good idea to use function calls as default values for arguments, because these functions are called only once (when the interpreter parses your code), and not each time you call the function.

The standard solution for such case is to use None as default value. Here:

def MoveTo(x=None, y=None):
  if x is None: x = t.xcor()
  if y is None: y = t.ycor()
  print 'x:', x, 'y:', y
  t.penup()
  t.goto(x, y)
  t.pendown()
  t.seth(0)

So when calling MoveTo(y=50), x will be replaced by the turtle current’s x coordinate, as you want.