Using Loops for Drawing Creating patterns with loops. Drawing spirals and concentric shapes. Generating fractals (e.g., Koch snowflake, Sierpinski triangle).
Using loops for drawing can create intricate patterns and designs. Let's explore a few examples: drawing spirals, concentric shapes, and generating fractals like the Koch snowflake and the Sierpinski triangle.
1. Drawing Spirals
A spiral can be created by incrementally increasing the radius while moving in a circular pattern. Here's an example using Python and the Turtle graphics module:
Python Code
import turtle
def draw_spiral():
t = turtle.Turtle()
t.speed(0)
t.color("blue")
for i in range(100):
t.forward(i * 2)
t.right(45)
turtle.done()
draw_spiral()
2. Drawing Concentric Shapes
Concentric shapes are multiple shapes that share the same center. Here's an example of drawing concentric circles:
Python Code
import turtle
def draw_concentric_circles():
t = turtle.Turtle()
t.speed(0)
t.penup()
t.goto(0, -50)
t.pendown()
for i in range(1, 11):
t.circle(i * 10)
t.penup()
t.goto(0, -i * 10)
t.pendown()
turtle.done()
draw_concentric_circles()
3. Generating Fractals
Koch Snowflake
The Koch snowflake is created by recursively adding smaller triangles to each side of a larger triangle. Here's an example using Python and Turtle:
Python Code
import turtle
def koch_snowflake(length, depth):
if depth == 0:
turtle.forward(length)
else:
length /= 3.0
koch_snowflake(length, depth-1)
turtle.left(60)
koch_snowflake(length, depth-1)
turtle.right(120)
koch_snowflake(length, depth-1)
turtle.left(60)
koch_snowflake(length, depth-1)
def draw_snowflake(length, depth):
for _ in range(3):
koch_snowflake(length, depth)
turtle.right(120)
turtle.done()
turtle.speed(0)
draw_snowflake(300, 4)
Sierpinski Triangle
The Sierpinski triangle is a fractal created by recursively subdividing an equilateral triangle into smaller triangles. Here's an example using Python and Turtle:
Python Code
import turtle
def sierpinski_triangle(vertices, depth):
if depth == 0:
turtle.penup()
turtle.goto(vertices[0])
turtle.pendown()
turtle.goto(vertices[1])
turtle.goto(vertices[2])
turtle.goto(vertices[0])
else:
mid1 = midpoint(vertices[0], vertices[1])
mid2 = midpoint(vertices[1], vertices[2])
mid3 = midpoint(vertices[2], vertices[0])
sierpinski_triangle([vertices[0], mid1, mid3], depth-1)
sierpinski_triangle([vertices[1], mid1, mid2], depth-1)
sierpinski_triangle([vertices[2], mid2, mid3], depth-1)
def midpoint(point1, point2):
return [(point1[0] + point2[0]) / 2, (point1[1] + point2[1]) / 2]
def draw_sierpinski_triangle(length, depth):
vertices = [[-length / 2, -length / 2], [0, length / 2], [length / 2, -length / 2]]
sierpinski_triangle(vertices, depth)
turtle.done()
turtle.speed(0)
draw_sierpinski_triangle(400, 4)
These examples demonstrate how to use loops and recursion to create interesting patterns and fractals. Adjust the parameters like length and depth to see different variations of these patterns.
Top of Form