tree.py

Created by vnap0v

Created on May 01, 2025

790 Bytes

This program draws a tree using recursive function calls. It uses the turtle module for the drawing. Tested on the calculator using software version 23.2.6.


from turtle import *

angle = 45
main_branch = 27
colors = ("green","yellow","orange","red","brown","black")

def draw(branch_size, branch_length):
    pensize(branch_size)
    color(colors[branch_size - 1])
    forward(branch_length)

def branch(depth):
    if depth > 0:
        h = heading()
        p = position()
        draw(depth, main_branch)
        branch(depth - 1)
        penup()
        goto(p)
        setheading(h + angle)
        pendown()
        draw(depth, main_branch // 2)
        branch(depth - 1)
        penup()
        goto(p)
        setheading(h - angle)
        pendown()
        draw(depth, main_branch // 2)
        branch(depth - 1)
    else:
        return()

speed(10)
hideturtle()
setheading(90)
goto(0,-80)
draw(6,main_branch + 10)
branch(5)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.