Advanced âĸ Python
Turtle Drawing
đĸ Meet the Turtle
The turtle module gives us a little turtle that draws a line wherever it walks. We import turtle and create our turtle with turtle.Turtle(). t.forward(100) moves the turtle forward 100 steps, and turtle.done() keeps the drawing window open.
import turtle
t = turtle.Turtle()
t.forward(100)
turtle.done()đĸ The turtle draws a straight line 100 steps long!
đ Everything in Turtle Drawing
Meet the Python turtle! Move it forward, turn it left and right, and use loops, colors, and functions to draw squares, triangles, stars, and your own art. Here is every step in this topic in one place, so you can review what you learned or jump straight to a step.
đĸ Meet the Turtle
The turtle module gives us a little turtle that draws a line wherever it walks. We import turtle and create our turtle with turtle.Turtle(). t.forward(100) moves the turtle forward 100 steps, and turtle.done() keeps the drawing window open.
import turtle t = turtle.Turtle() t.forward(100) turtle.done()âĒī¸ Turning Left and Right
The turtle can turn using left() and right(). The number inside is the angle in degrees. A turn of 90 is a corner, like the corner of a book, and a turn of 360 is a full spin.
import turtle t = turtle.Turtle() t.forward(100) t.left(90) t.forward(100) turtle.done()âŦ Drawing a Square with a Loop
A square has 4 equal sides and 4 corners of 90 degrees. Instead of writing forward and left four times, we can use a for loop to repeat them. Loops make drawing much faster!
import turtle t = turtle.Turtle() for i in range(4): t.forward(100) t.left(90) turtle.done()â Triangles and Stars
A triangle has 3 sides, so the turtle turns 120 degrees 3 times. A star has 5 points, and the turtle turns 144 degrees each time. Changing the number of repeats and the angle makes totally different shapes!
import turtle t = turtle.Turtle() for i in range(3): t.forward(100) t.left(120) t.penup() t.forward(150) t.pendown() for i in range(5): t.forward(100) t.right(144) turtle.done()đ¨ Colors and the Pen
We can change how the turtle draws. color() changes the pen color, and pensize() makes the line thicker. penup() lifts the pen so the turtle moves without drawing, and pendown() puts it back. begin_fill() and end_fill() color in a shape.
import turtle t = turtle.Turtle() t.pensize(5) t.color("purple") t.fillcolor("pink") t.begin_fill() for i in range(4): t.forward(100) t.left(90) t.end_fill() turtle.done()đ ī¸ Drawing with Functions
We can put drawing code inside a function and use it again and again. A parameter like size lets us draw shapes of different sizes with the same function. This is how artists make patterns quickly!
import turtle t = turtle.Turtle() def draw_square(size): for i in range(4): t.forward(size) t.left(90) draw_square(50) draw_square(100) draw_square(150) turtle.done()
