Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

if statement - Unable to understand this recursive turtle python code

this is my first time asking a question, I hope some of you will find time to answer.

So my goal is to write a python script using the turtle module to code a pythagoras tree.

I've spent days on it, and I really couldn't advance past a certain point, so I looked online to help me. I've found a code that does what I want but with very little lines of code:

import turtle
t = turtle.Pen()




LIMIT  =11
SCALAR = 0.5 * (2 ** 0.5)


def drawTree(size, depth):

    drawSquare(size)

    if depth + 1 <= LIMIT:

        t.left(90)
        t.forward(size)
        t.right(45)
        drawTree(size * SCALAR, depth + 1)

        t.forward(size * SCALAR)
        t.right(90)
        drawTree(size * SCALAR, depth + 1)

        t.left(90)
        t.backward(size * SCALAR)
        t.left(45)
        t.backward(size)
        t.right(90)



def drawSquare(sideLength):

    for i in range(4):
        t.forward(sideLength)
        t.left(90)



t.up(); t.goto(-100, -200); t.down()
drawTree(170.0, 0)

So I understand most of the code, except the second and the third paragraph of the "if": why do they ever get executed? If the function keeps repeating itself, it never reaches that point normally! I'm sure that I'm missing something really easy here and I hope y'all understood my question :) thanks again!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For example, "depth" is 10 and program called drawTree(size * SCALAR, 10 + 1) in first paragraph. "depth" becomes 11, IF is false and program returns back to drawTree, where "depth" is 10. And then program executes next line, first line in second paragraph.

In exactly the same way, program called drawTree() in second paragraph, while "depth" not reaches LIMIT, then returns back and go to first line of third paragraph.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...