In my post on functions, I used the the example of a little program that draws a square. I didn’t say anything about the “turtle” command. It’s pretty obvious what happens though. When you use this command, Python opens a graphic window and draws things. The idea of turtle graphics began in the Logo programming language in the 1960s. The idea was that there was a virtual “turtle” which you could control with simple commands. If you have used “Scratch”, you have been using a version of Logo. I am going to use this post to review a few of the basics.
Here’s a little Scratch program that draws a square:
It’s not a very good program though. There’s no need for it to be that long, or to repeat itself so much. We can make it more elegant by using a loop.
We’ve done the same thing with 4 lines of code, instead of 9. Another advantage is that if we want to change something (the size of the square for instance), we only need to make the change once. Also, cutting down on repetition of lines of code makes it less likely that we’ll type something in wrong, and easier to put right if we do. Smart programmers are lazy – but in a good way. They write programs that are as simple and elegant as possible.
Okay, this program works, but it’s a bit dull. It just does the same thing every time we run it. But we can change that by using a variable. Let’s switch to Python now.
This is basically the same program I used in the post on functions, but now I have added the use of a variable, so that the program will draw a square the size that the user wants.
But what if I want a triangle or some other shape? Well, we can re-write the program quite simply to make it even more flexible.
Now we have a nice simple program that can draw a very wide range of different shapes. Which is nice 😉