A square with a loop
import turtle t = turtle.Turtle() t.color("blue") t.width(3) for i in range(4): t.forward(120) t.right(90)
Write Python. Understand every error.
Fun with Python · topic 25 of 25
The turtle module lets you draw pictures with code. Imagine a small turtle holding a pen, sitting in the middle of the screen and facing right. You give it instructions, and it draws a line wherever it walks.
import turtle t = turtle.Turtle() t.forward(100) # walk 100 steps t.left(90) # turn 90 degrees to the left t.forward(100)
The drawing appears in the Output panel when your program finishes. Every shape is just a sequence of walks and turns, which makes turtle a perfect way to practise loops.
t.forward(n) and t.backward(n) move the turtlet.left(angle) and t.right(angle) turn itt.penup() lifts the pen, t.pendown() puts it backt.color("red") changes the pen colour, t.width(3) makes lines thickert.goto(x, y) jumps to a point; the centre is (0, 0)t.circle(r) draws a circle of radius rA regular shape with n sides needs n equal walks and n equal turns. The turns always add up to 360 degrees, so each turn is 360 / n degrees. With a loop, one pattern can draw a triangle, a square or an octagon just by changing n.
import turtle t = turtle.Turtle() sides = 6 for i in range(sides): t.forward(80) t.left(360 / sides)
Drawing programs cannot be checked automatically like the other exercises, because the result is a picture, not printed text. The Practice tab gives you creative challenges instead: compare your drawing with the description.
forward, left and right move and turn it.penup() lifts the pen so the turtle can move without drawing, and pendown() puts it back.penup() before goto(), which draws a line to the new position.t = turtle.Turtle(). Read the NameError guide.
import turtle t = turtle.Turtle() t.color("blue") t.width(3) for i in range(4): t.forward(120) t.right(90)
import turtle t = turtle.Turtle() for sides, colour in [(3, "red"), (5, "green"), (8, "blue")]: t.color(colour) for i in range(sides): t.forward(60) t.left(360 / sides)
import turtle t = turtle.Turtle() colours = ["red", "orange", "gold", "green", "blue"] for i in range(5): t.color(colours[i]) t.forward(150) t.right(144)
import turtle t = turtle.Turtle() t.color("purple") for i in range(12): t.circle(50) t.left(30)
import turtle t = turtle.Turtle() for x in [-150, -50, 50, 150]: t.penup() t.goto(x, 0) t.pendown() t.circle(30)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
t.forward(100) and t.left(90), which way does the turtle face if it started facing right?left(90) turns it 90 degrees anticlockwise, from facing right to facing up.
forward(100) and right(90) to draw a square?A square has 4 equal sides and 4 turns of 90 degrees.
The turns add up to 360 degrees: 360 / 6 = 60.
t.penup() do?Use penup() to move without a line, and pendown() to draw again.
A triangle has 3 sides and each turn is 360 / 3 = 120 degrees.