r/learnpython • u/Confident-Acadia4217 • 1d 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
2
Upvotes
2
u/DHTechdev 1d ago •
A full tree needs recursion instead of a while True loop. Write a function that takes a size and a depth, draws one square, then calls itself twice for the two smaller squares on top, each with side size divided by 1.414, one turned left 45 degrees and one turned right. Stop when depth hits 0. After each branch, send the turtle back to where it started so the second branch begins in the right spot.
1
u/Sufficient-Tale6131 1d ago •
Recursion is the way, and since you already draw the square with rt(90) the turns work out pretty neatly. Roughly: def tree(size, depth). If depth is 0 just return. Otherwise draw the square like you do now, then fd(size) so you're at the top-left corner. lt(45) and call tree(size * 0.7071, depth - 1), that's the left branch. Then rt(90) and fd(size * 0.7071), which puts you at the tip of the triangle already facing the right way, and call tree again for the right branch. After that undo the moves in reverse: bk(size * 0.7071), lt(45), bk(size).
The important part is that every call leaves the turtle exactly where and how it found it, otherwise the branches drift. Start with lt(90) so it grows upward, and put tracer(0) at the start and update() at the end, depth 8 or so is painfully slow to watch otherwise.
1
u/Free-Good9203 1d ago
the trick with `turtle` recursion is saving `pos = t.pos()` and `ang = t.heading()` right after drawing a square, then restoring them with `t.penup(); t.goto(pos); t.setheading(ang); t.pendown()` before starting the second branch. scale each child side by `size / (2 ** 0.5)` and stop once `depth == 0` so it terminates cleanly.
1
u/PracticalToolsLab_TW 22h 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:
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.