Drawing a square
Take a look at this program:
The program starts by importing turtle and choosing a color. The turtle walks along four straight lines that make up the four sides of a square. But how large should it be? That is decided by how far the turtle walks, which is the value contained in the distance variable which must be entered by the user.
Try running the program above and try entering a small value, like 50, and a large value, like 150.
Picking the angle
Just like for distance we can also use input to ask for an angle to turn.
# Import the turtle, choose a drawing color and a pen shape. import turtle turtle.color('red') turtle.shape('turtle') # Call the input function and formulate the questions to the user. distance = int(input("How long?")) angle = int(input(“angle?”)) # Use the distance and angles that the user specified. turtle.forward(distance) turtle.left(angle) turtle.forward(distance) turtle.left(angle) turtle.forward(distance) turtle.left(angle) turtle.forward(distance)
What happens if you enter something other than 90 for the angle?
Also, try adding another two lines to the code:
And enter the angle 108.
Walking without drawing
We can add the two instructions penup() and pendown() if the turtle should move without drawing.
For example, add the following line directly after the two input lines:
The turtle will move the same distance, but will not draw anything.
If you want it to start drawing again, you can later add:
You can use these instructions (and others) as often as you want in your program.
Can you make the turtle draw your favorite shape?
A turtle that follows instructions
In addition to entering instructions via text (with input) we can also control the program by clicking directly on the window/screen where the turtle is or press somewhere on the keyboard.
To do that, we must first get access to the turtle screen/window:
screen = turtle.Screen()
Then, we can tell the turtle to always go to the point we're clicking on.
Finally, we tell the program to keep listening for new mouse clicks.
Here is the complete example:
Import turtle turtle.color(‘red’) screen = turtle.Screen() screen.onclick(turtle.goto) screen.listen()
Try it out!
In this video we combine input, turtle, and screen to create an interactive turtle.
- I/O: Short for input/output. In Python we use the functions input and print.
- Variable: A part of the computer's memory where we can store something, like a piece of text, a name, or any number.