r/learnpython • u/Confident-Acadia4217 • 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
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:
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.