PY-1.1-BP2-MQ40

Our Goal

We will write a Python program that makes our turtle draw a square spiral. This means the lines will get longer as the turtle draws, making a cool spiral shape.

Check Your Work

Before we start, let's run the tests to see what we need to fix.

Run this command in your terminal: pytest module-1.1/blueprint-2/quest-40

What you should see:

  • test_draw_square_spiral_logic

Write Your Code

Now, let's write our Python code to draw a spiral. Remember, you'll need to set up your drawing screen, create a turtle, and then use commands to make it draw.

Here are some helpful code examples from the Turtle documentation:

1. Start your program:

import turtle

2. Set up your drawing screen:

screen = turtle.Screen()
screen.setup(width=650, height=450)
screen.bgcolor("lightgray")

3. Make a turtle:

my_turtle = turtle.Turtle()

4. Basic Movement and Turning:

my_turtle.forward(80)
my_turtle.left(90)

5. Creating Growing Patterns (Spirals):

# To make a spiral, you need to draw lines that get longer each time.
# You can use a loop to repeat drawing a line and turning.
for i in range(some_number_of_segments):
    # Inside the loop, make the line length grow (e.g., add a small number each time).
    # Then, draw a line with the new length.
    # For a square spiral, you would turn 90 degrees after each line.

6. Keep the window open:

screen.exitonclick()
# OR
# turtle.done()

Check Your Work Again

Now, let's run the tests again to see if your code works.

Run this command in your terminal again: pytest module-1.1/blueprint-2/quest-40

What you should see:

  • test_draw_square_spiral_logic

Documentation

Repeating with Loops: The Power of Patterns

Loops are fundamental programming constructs that allow a block of code to be executed repeatedly. This is essential for automating tasks, processing sequences of data, and creating repetitive patterns in graphics.

The for Loop with range()

The for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range). The range() function is commonly used with for loops to repeat an action a specific number of times.

  • Basic Syntax:

    for variable in sequence:
        # Code block to be repeated
        # This code is indented
    # Code outside the loop (not repeated)
    
  • Using range(stop): range(stop) generates a sequence of numbers starting from 0, up to (but not including) the stop number.

    # This loop will run 5 times, with 'i' taking values 0, 1, 2, 3, 4
    for i in range(5):
        print(i)
    

    Console output showing numbers 0, 1, 2, 3, 4 on separate lines

  • Using range(start, stop): range(start, stop) generates a sequence of numbers starting from start, up to (but not including) the stop number.

    # This loop will run 3 times, with 'j' taking values 2, 3, 4
    for j in range(2, 5):
        print(j)
    
  • Repeating an Action a Fixed Number of Times: If the loop variable itself is not needed within the loop, it's common practice to use an underscore _ as the variable name.

    # This loop will run 3 times, printing the message each time
    for _ in range(3):
        print("Hello!")
    

    Console output showing "Hello!" printed 3 times

Loops in Turtle Graphics

Loops are particularly effective with Turtle graphics for drawing repetitive shapes and patterns efficiently. Instead of writing the same drawing commands multiple times, a loop can execute them repeatedly.

  • Basic Turtle Setup: To use Turtle graphics, you need to import the module and create a Turtle object.

    import turtle
    
    # Create a turtle object (often called 'pen' or 'artist')
    my_turtle = turtle.Turtle()
    
    # Optional: Adjust speed (0 is fastest, 1-10 are slow to fast)
    # my_turtle.speed(0)
    
    # Optional: Hide the turtle icon
    # my_turtle.hideturtle()
    
    # Optional: Keep the window open (usually at the end of the script)
    # turtle.done()
    

    Basic turtle setup code

  • Basic Movement and Drawing Commands:

    • forward(distance): Moves the turtle forward by distance.
    • backward(distance): Moves the turtle backward by distance.
    • left(angle): Turns the turtle left by angle degrees.
    • right(angle): Turns the turtle right by angle degrees.
    • penup(): Lifts the pen up, so movement does not draw.
    • pendown(): Puts the pen down, so movement draws.
    • goto(x, y): Moves the turtle to the absolute position (x, y).
    • circle(radius): Draws a circle with the given radius.
  • Repeating Drawing Actions: A loop can repeat the commands needed to draw a simple shape.

    import turtle
    
    pen = turtle.Turtle()
    
    # Draw a square using a loop
    side_length = 100
    for _ in range(4): # A square has 4 sides
        pen.forward(side_length)
        pen.left(90) # Turn 90 degrees for a square
    
    # turtle.done()
    

    Turtle drawing a single square

  • Drawing Multiple Identical Shapes: A for loop can repeat the drawing commands for a single shape multiple times, with movement commands in between to position each new shape.

    import turtle
    
    pen = turtle.Turtle()
    pen.speed(0) # Fastest speed
    
    shape_size = 40
    spacing = 10
    
    # Draw two triangles side-by-side
    for _ in range(2): # Repeat 2 times for 2 triangles
        # Draw one triangle (3 sides, 120 degree turns)
        for _ in range(3):
            pen.forward(shape_size)
            pen.left(120)
        
        # Move to the next position without drawing
        pen.penup()
        pen.forward(shape_size + spacing) # Move horizontally
        pen.pendown()
    
    # turtle.done()
    

    Turtle drawing two triangles side-by-side

  • Drawing Regular Polygons: Loops simplify drawing regular polygons by repeating the actions of drawing a side and turning. The external angle for any regular polygon is 360 / number_of_sides.

    import turtle
    
    pen = turtle.Turtle()
    
    num_sides = 5 # For a pentagon
    side_length = 80
    angle = 360 / num_sides # Calculate the external angle
    
    # Draw the polygon
    for _ in range(num_sides):
        pen.forward(side_length)
        pen.left(angle) # Turn by the calculated external angle
    
    # turtle.done()
    

    Turtle drawing a pentagon

  • Drawing Shapes with Changing Properties: The loop variable can be used within the loop to dynamically alter properties of the shapes being drawn, such as size or position.

    import turtle
    
    pen = turtle.Turtle()
    pen.speed(0)
    pen.hideturtle()
    
    # Draw circles with increasing radii
    base_radius = 10
    num_circles = 4
    
    for i in range(num_circles):
        current_radius = base_radius * (i + 1) # Radius increases: 10, 20, 30, 40
    
        # Position for concentric circles (move to bottom edge)
        pen.penup()
        pen.goto(0, -current_radius)
        pen.pendown()
    
        pen.circle(current_radius)
    
    # turtle.done()
    

    Turtle drawing concentric circles

  • Creating Growing Patterns (Spirals): By systematically modifying a movement or drawing parameter (like line length) in each iteration, growing patterns like spirals can be created.

    import turtle
    
    pen = turtle.Turtle()
    # pen.speed(0) # Optional: faster drawing
    
    initial_step = 5
    num_segments = 15
    turn_angle = 90 # For a square spiral
    
    for i in range(num_segments):
        # Calculate distance: 5 * (0+1)=5, 5*(1+1)=10, ..., 5*(14+1)=75
        distance = initial_step * (i + 1)
        
        pen.forward(distance)
        pen.right(turn_angle)
    
    # turtle.done()
    

    Turtle drawing a square spiral

  • Drawing Complex Shapes (Stars): Leveraging for loops with specific angle calculations allows for drawing complex, non-convex geometric shapes like stars through repeated line-and-turn sequences. For a 5-pointed star, the external turn angle is 144 degrees.

    import turtle
    
    pen = turtle.Turtle()
    
    num_points = 5
    side_length = 100
    star_angle = 144 # Specific angle for a 5-pointed star
    
    # Draw the star
    for _ in range(num_points):
        pen.forward(side_length)
        pen.right(star_angle)
    
    # turtle.done()
    

    Turtle drawing a 5-pointed star

  • Nested Loops: One loop can be placed inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop. This is useful for drawing patterns like grids.

    # Example of nested loops printing coordinates
    for row in range(2): # Outer loop runs 2 times (row 0, row 1)
        for col in range(3): # Inner loop runs 3 times for *each* row iteration
            print(f"Row {row}, Col {col}")
    # Output:
    # Row 0, Col 0
    # Row 0, Col 1
    # Row 0, Col 2
    # Row 1, Col 0
    # Row 1, Col 1
    # Row 1, Col 2
    

    In Turtle graphics, nested loops can be used to repeat a shape-drawing process (inner loop) multiple times while moving the turtle between shapes (outer loop).

    # Sketch: Drawing a row of shapes using nested loops
    # Outer loop: Repeat for each shape in the row
    #   Inner loop: Draw one complete shape (e.g., a square)
    #   Move turtle to the start position of the next shape
    

    Turtle drawing a pattern using nested loops, e.g., a grid of squares or circles