Today's lab will focus on turtle graphics. An excellent overview of turtle graphics can be found at the http://interactivepython.org/runestone/static/thinkcspy/PythonTurtle/helloturtle.html.
Let's start with a simple program:
import turtle def main(): daniel = turtle.Turtle() #Set up a turtle named "daniel" myWin = turtle.Screen() #The graphics window #Draw a square for i in range(4): daniel.forward(100) #Move forward 10 steps daniel.right(90) #Turn 90 degrees to the right myWin.exitonclick() #Close the window when clicked main()The first line:
import turtleloads the turtle graphics module. Like the math library, the turtle graphics library is a standard part of python but needs to be imported to be used in your program.
We next define the main() function and set up two turtle graphics objects:
daniel = turtle.Turtle() #Set up a turtle named "daniel" myWin = turtle.Screen() #The graphics windowThe first line creates a turtle, named daniel. The next line creates a new window, where the graphics will appear.
The main() function has a loop that has two commands:
What happens when these commands are repeated 4 times? Try running the program to see what is drawn.
Let's make two small changes to our program:
import turtle def main(): daniel = turtle.Turtle() #Set up a turtle named "daniel" myWin = turtle.Screen() #The graphics window #Draw a square for i in range(50): daniel.forward(i) #Move forward 10 steps daniel.right(90) #Turn 90 degrees to the right myWin.exitonclick() #Close the window when clicked main()
Run you program (choose "Run Module" from the "Run" menu, or F5). What is drawn? How can you make it fill the entire window?
What happens if we had left the steps forward never changing (but a bit shorter (10 instead of 100) so it appears on the screen), but instead changed the right turn from 90 degrees to i degrees:
import turtle def main(): daniel = turtle.Turtle() #Set up a turtle named "daniel" myWin = turtle.Screen() #The graphics window #Draw a square for i in range(50): daniel.forward(10) #Move forward 10 steps daniel.right(i) #Turn 90 degrees to the right myWin.exitonclick() #Close the window when clicked main()
Some basic turtle commands are:
With the remaining time, work on the homework programs.