Python - #6 - Turtle

1. Importing turtle

The turtle library stores all of the code to create and move an object called a turtle

The turtle library must be imported into your Python program before you can use it to draw lines, shapes and colours.

Task 1 - Create a new Python program and save the file as Python-Turtle.py

Copy the import turtle code at the start of your program.

2. Basic Shapes

The turtle can be controlled by writing how many pixels it should travel forward and the angle it should point left or right.

Moving Forwards

turtle.forward(100) will move the turtle forward by 100 pixels.

turtle.forward(200) will move the turtle forward by 200 pixels.

When using the left command or the right command, the turtle won't actually move, but it will rotate by the number of degrees that you state.

For example, typing turtle.left(90) will point the turtle upwards.

Rotating Left & Right

Task 2 :

Copy the code to the right to make the turtle draw a square.

Then, in new windows, try to make:

  1. A Rectangle

  2. A Triangle

  3. A Pentagon

  4. A Hexagon

Square

Rectangle

Triangle

Pentagon

Hexagon

Hint: To work out the angles, divide 360 by the number of sides.

3. Using Loops

You can use a for loop to repeat code.

This is especially helpfully with intricate shapes with many sides.

The code below will print a square but in only 3 lines instead of the 8 lines from task 2.

This is the number of times the code underneath will be repeated.

Change it to a higher number to repeat it more often.

Each line after the 'for num in range' line must be indented.

Press the tab key once on your keyboard to indent your code.

Task 3 - Copy the code above to make the turtle draw a square using a loop.

Then, in new windows, try to make:

  • A Heptagon

  • An Octagon

  • A Circle

  • A Pentagram (5-sided Star)

Square

Heptagon

Octagon

Circle

Pentagram

Hint: To work out the angles, divide 360 by the number of sides.

4. Advanced Features

Choose a background colour

window = turtle.Screen()

window.bgcolor("red")

   

Choose the line size and colour

turtle.pensize(6)

turtle.color("green")

 

Fill a shape

turtle.color("yellow")

turtle.begin_fill()

 

(put your turtle's directions in here)

 

turtle.end_fill()

Lift the pen

turtle.penup()
turtle.pendown()

 

Speed up/Slow down the turtle

turtle.speed(speed=10)

Task 4 - Use the code above to make:

  • A blue square on a red background.

  • A yellow triangle on a pink background.

  • Two different coloured circles - not touching each other.

  • Three different shapes of three different colours - not touching each other.

Complex Shapes

Use everything that you have learned on this page to help you create more complex shapes.

You could try:

  • A Flower

  • A Word (like your name - you will need to use the penup() and pendown() commands.

  • A Christmas tree

  • A Landscape (green ground, blue sky, yellow sun)

© CSNewbs 2020