In this article we will cover :
- The importance of typing exactly
- Drawing in Python using Turtle
- Why we use variables and loops
First off, open up IDLE! This is the editor we will be using for writing Python. Python is a popular programming language used all over the world.
IDLE has two modes we can use :
Interactive Mode Here we can type commands the computer can understand and it will run immediately. This is good for playing around and learning how things work. It will not save your work.
If we click file we can create a new file
This will let us write a program. Here the code is saved so we can refer back to it later!
Drawing using Turtle
Let's begin by playing with a tool in Python called Turtle. This allows us to draw complicated patterns. We will limit ourselves initially to two commands :
- forward(units) - Moves the turtle forward units steps
- left(degrees) - Turns the turtle left by degrees degrees
- right(degrees) - Turns the turtle right by degrees degrees
if we're ever unsure about how something works in Python we can use help like so
Try getting the following code to work
is made using
import turtle as tl tl.forward(100)
and a square can be drawn like so
import turtle as tl tl.forward(100) tl.left(90) tl.forward(100) tl.left(90) tl.forward(100) tl.left(90) tl.forward(100) tl.left(90)
Exercise Set 1 1. Write the code to draw the following shapes
In these cases we should notice how tedious it is to manually type the same lines of code over and over.
The most important principle to learn in programming is called DRY. This stands for DON'T REPEAT YOURSELF. This means that we need to find a way to stop typing the sames lines over and over. We want to avoid doing this, as it is hard to alter and easy to make mistakes!
For example, a square can be written as
import turtle as tl for _ in range(4): tl.forward(100) tl.left(90)
Here we have used a for loop. In this case it will repeat 4 times. We will explore how this works in more detail, in future classes. Remember you can use help(range) to find out more information!
Exercise Set 2
- Rewrite the code for the previous shapes with loops
- Draw the following spiral
Here we can see we need to use variables. These are objects with names that can hold numbers, text and other useful things.
import turtle as tl side = 100 angle = 90 sides = 4 loops = 5 increase_by = 10 for _ in range(loops*sides): tl.forward(side) tl.left(angle) side = side + increase_by tl.exitonclick()
Exercise Set 3
- Alter just the variables to produce the following patterns
- Draw the following patterns
Today we have looked at using the left and forward commands in turtle with a for loop and variables.