r/learnpython • • 9d ago

pythagoras tree

I made code for one "branch" of the Pythagoras tree, and I have no idea how to make the full tree. Can someone help? My code:

from turtle import*
x=100
while True:
    for i in range (4):
        fd(x)
        rt(90)
    rt(90)
    fd(x)
    lt(45)
    xNaDwa= x*x/2
    y= xNaDwa**0.5
    x=y
3 Upvotes

5 comments sorted by

View all comments

1

u/PracticalToolsLab_TW 8d ago

Your single branch is already close, the missing piece is recursion. A while True loop can only follow one path, but the tree splits in two at every square, so you need a function that calls itself twice and then returns to where it started.

Here is a version that should run as is:

from turtle import *

def tree(side, depth):
    if depth == 0:
        return
    start, ang = pos(), heading()

    # draw the square upward from the base
    for _ in range(4):
        fd(side)
        lt(90)

    # go to the top-left corner of the square
    lt(90); fd(side); rt(90)
    top_left = pos()
    child = side / 2 ** 0.5

    # left branch: base starts at top-left corner, turned 45 degrees left
    lt(45)
    tree(child, depth - 1)

    # right branch: base starts at the triangle's apex, turned 45 degrees right
    penup(); goto(top_left); setheading(ang + 45); fd(child); rt(90); pendown()
    tree(child, depth - 1)

    # return to the start so the caller can continue
    penup(); goto(start); setheading(ang); pendown()

speed(0)
tracer(0)
penup(); goto(-50, -250); pendown()
tree(100, 9)
update()
done()

Why it works: the two child squares sit on the two short sides of a right triangle placed on top of the parent square, so each has side = parent / sqrt(2), and they are rotated 45 degrees left and right. Every call saves its start position and heading and restores them at the end, which is what lets the second branch start in the right place. Depth is the stopping condition (depth 9 means 2^9 - 1 squares). Start with a small depth like 4 to see the shape.