[igCS] For-loop Drawing

Introducing Turtle Graphics

  • Open REPL.it, start a new REPL project of Turtle-Graphics
  • On first two lines, enter:
    import turtle
    t = turtle.Turtle()
  • Try the following commands:
    • t.forward(50)
    • t.backward(50)
    • t.left(90)
    • t.right(90)

Drawing basic shapes with for loop

Pentagon of each side 15 units

Decagon of each side 10 units

New commands

  • setcolor( (r, g, b) )
    • Note there's one more bracket around the rgb value
    • The range of RGB is 0-255, e.g.
    • setcolor( (255, 255, 255) )  - white
    • setcolor( (255, 0, 0) ) - Red
  • setpos( x, y )
    • Move the turtle to the absolute position
  • penup() , pendown()

Let's try to draw this

Copy this pattern in the notebook, write down the step by step sequence for it:

t.fd(   )
t.lt(   )
t.fd(   )
t.lt(   )
t.fd(   )
t.lt(   )
t.fd(   )
t.lt(   )

What is the pattern?

t.fd(    )
t.lt(90)

 

fd is just repeating with different number!

What is the formula for the pattern? 

What is the range for the pattern?

 

while width in range([start], [stop-1]):
  t.fd( [formula with width] )
  t.lt(90)
  1. Complete the Square spiral,
  2. Try with a triangle pattern,
  3. You can also ask user input the number of repeat and number of sides you want for a spiral generator

Extra challenge - combining with color function

Nested For Loops

  • Any blocks in Python can be "nested"
  • If we nested for loop, we can make some interesting patterns from it. 

Plotting graphs with Turtle

  • Use setpos(x,y) to plot
  • Try finding some interesting functions online and plot it using Python turtle
  • Screenshot and share on Classroom!

[iGCS] For-loop Drawing

By Andy tsui

[iGCS] For-loop Drawing

  • 152