0

I need help understanding how this function works:

import turtle

annie = turtle.Turtle()

def draw(t, length, n):

    if n == 0:
        return
    angle = 50
    t.fd(length*n)
    t.lt(angle)
    draw(t, length, n-1)
    t.rt(2*angle)
    draw(t, length, n-1)
    t.lt(angle)
    t.bk(length*n)

draw(annie, 30, 4)

turtle.mainloop()

This function creates a symmetrical branched graphic with a large Y shaped branch, with two smaller Y shaped branches hanging off the end of each arm of the larger Y shaped branch. The function ends with the "turtle" (the little arrow that leaves a line behind it as it moves across the screen) going backwards four times from the tip of the final smaller branch it draws and finishing where it started at the beginning of the larger branch. So how does n = 4 by the time the function finishes if the self calls before that statement subtract 1 from the value of n? And does the first self call iterate through the first few lines of the function back to that self call until n = 0, then move through the rest of the function? In which case, what is the value of n for the first instance of the second self call statement? 4? 0? I think I clearly am misunderstanding something and would appreciate any resources to help me know what I'm doing.

Random Davis
  • 6,662
  • 4
  • 14
  • 24

1 Answers1

0

The reason that n is still 4 when the outermost function finishes is that each function has its own copy of n. Each function works in its own scope.

The outermost function passes the value of n to the next function. So each subsequent function creates it's own copy and subtracts 1 from the copy, never touching the n in the outermost functions scope.

This works different for lists, objects, etc. though.

wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29