Search code examples
pythonpython-turtle

Write a void (non-fruitful) function to draw a square. Use it in a program to draw the image shown below. Assume each side is 20 units


Write a void (non-fruitful) function to draw a square. Use it in a program to draw the image shown below. Assume each side is 20 units. (Hint: notice that the turtle has already moved away from the ending point of the last square when the program ends.)

I am required to draw as such:

enter image description here

Here is the sample of my code

import turtle
def draw_square(t, sz):
    """Get turtle t to draw a square with sz side"""

    for i in range(4):
        t.forward(sz)
        t.left(90)


def main():
    wn = turtle.Screen()
    wn.bgcolor("white")

    alex = turtle.Turtle()
    alex.color("Blue")

    draw_square(alex, 20)

    wn.exitonclick()


if __name__ == "__main__":
    main()

Solution

  • Here, I programmed it for you. It draws the squares making use of a nested for loop.

    Here is the code:

    import turtle
    def draw_square(t, sz):
        """Get turtle t to draw a square with sz side"""
        for i in range(5):
            for i in range(4):
                t.forward(sz)
                t.left(90)
            t.penup()
            t.forward(sz + (sz))
            t.pendown()
    
    def main():
        wn = turtle.Screen()
        wn.bgcolor("white")
    
        alex = turtle.Turtle()
        alex.color("Blue")
    
        draw_square(alex, 20)
    
        wn.exitonclick()
    
    
    if __name__ == "__main__":
        main()
    

    And here is the output: enter image description here

    Hope this helps!