Control Flow: The for Loops

Drawing a Tree

              
              *
             ***
            *****
           *******
          *********
         ***********
        *************
       ***************
      *****************
     *******************
             ###
             ###
             ###
             ###
             ###

Using the earlier functions, we can display a tree on the console as in the following example:

def draw_isosceles_triangle_with_offset(height, offset):
    for h in range(height):
        for o in range(1, height - h + offset):
            print(" ", end='')

        for i in range(2*h+1):
            print("*", end='')

        print()


def draw_rectangle_with_offset(width_of_rectangle, height_of_rectangle, offset_of_rectangle):

    for h in range(height_of_rectangle):
        for o in range(1, offset_of_rectangle):
            print(" ", end='')

        for w in range(width_of_rectangle):
            print("#", end='')
        print()


def draw_tree(triangle_height, trunk_width, trunk_height, offset):
    draw_isosceles_triangle_with_offset(triangle_height, offset)
    rectangle_offset = offset + int(((2 * triangle_height + 1) - trunk_width) / 2)
    draw_rectangle_with_offset(trunk_width, trunk_height, rectangle_offset)


def main():
    triangle_height = 10
    triangle_offset = 5
    trunk_width = 3
    trunk_height = 5

    draw_tree(triangle_height, trunk_width, trunk_height, triangle_offset)


main()

Keep on practicing with the code above and try outputting multiple triangles on the tree.

              *
             ***
            *****
           *******
              *
             ***
            *****
           *******
              *
             ***
            *****
           *******
             ***
             ***
             ***

              *
             ***
            *****
              *
             ***
            *****
           *******
              *
             ***
            *****
           *******
          *********
         ***********
        *************
             ###
             ###
             ###
             ###
             ###