Draw a square



Turtle GraphicsBefore doing turtle graphics in Spyder, you must do the following. If you don't, you will have to manually kill the turtle graphics program window (possibly using the task manager) and re-open a new console window:Go to Tools | Preferences | iPython console | Graphics and change Backend to Automatic.Turtle graphics are not part of the basic part of the language. They are an add-on. Therefore, to use turtle graphics:import turtleWe need a turtle that we can give commands to. Create a turtle that you can move around the screen:t = turtle.Turtle()# create a turtleCreate a screen (window) for the turtle to walk around on:win = turtle.Screen()Set the screen size:win.setup(800, 600) # sets width to 800 and height to 600We need to set the screen's background color:win.bgcolor("light green")# you can also use r, g, b numbersSet the turtle's color:t.color("blue")Set the width of the turtle's pen (in pixels):t.pensize(2)Make the turtle move forward or backward:t.forward(100)t.backward(100)Pick the turtle's pen up or set it down:t.penup()t.pendown()Make the turtle turn relative to its current angle:t.left(90)t.right(90)Force the turtle to point in a given direction:t.setheading(0)# point rightt.setheading(90)# point upt.setheading(180)# point leftt.setheading(270)# point downt.setheading(-90)# point downForce the turtle to a specific location on the screen:t.goto(x, y)Draw a circle:t.circle(radius)Wait for the user to click the mouse and close the drawing window:win.exitonclick()Note: You may have to explicitly close the console (right side of screen) after each run of a turtle program.Here are all of the commands you need to start your program:import turtlet = turtle.Turtle()# create a turtlewin = turtle.Screen()win.setup(800, 600) # a default screen size will be used if you leave this outwin.bgcolor("light green")# you can also use r, g, b numberst.color("blue")t.pensize(2)And here is the command you need to end your program:win.exitonclick()Draw a squaret.fd(200)t.lt(90)t.fd(200)t.lt(90)t.fd(200)t.lt(90)t.fd(200)t.lt(90)Draw a hexagont.fd(200)t.lt(60)t.fd(200)t.lt(60)t.fd(200)t.lt(60)t.fd(200)t.lt(60)t.fd(200)t.lt(60)t.fd(200)t.lt(60)We can cut/paste, but there's an easier way. Use a loop.LoopsTo repeat 4 times:for i in range(4): # repeat four times, where i goes from 0 to 3 t.fd(200) t.left(90)To repeat 6 times:for i in range(6): # repeat six times, were i goes from 0 to 5 t.fd(200) t.left(60)The number of loops can also be a variable. So can the length of a side:sides = int(input("How many sides? ") or "8")length = int(input("How long is a side? ") or "100")color = input("What color? ") or "red"t.color(color)for i in range(sides): t.fd(length) t.left(360/sides)Draw a house.Draw a row of 5 houses. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download