Python Turtles

Python Turtles

Python turtles is a python library that allows for the creation of art with code. This is a great start for new programmers because it makes the fundamental programming concepts visual for learners.

Getting Started with Python Turtles


Importing the turtle library:


To be able to use python turtles begin by importing the library.


import turtle as t


Extra Information: A python library is collection of code that can be added to the existing code of python. It is like adding a new book to your bookshelf!


First Steps


Now that we have access to the library to make turtles work, let's begin by making our turtle move across the screen.


import turtle as t

t.forward(100)


Turning the Corner


Adding t.left to your code will rotate the turtle to the left by a set number of degrees. You can use t.right for turns to the right!


import turtle as t

t.forward(100)
t.left(90)


Challenges:


Write a program that draws a box


import turtle as t

t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)


Write a program that draws a triangle


import turtle as t

t.forward(100)
t.left(120)
t.forward(100)
t.left(120)
t.forward(100)
t.left(120)


Iteration:


Do you notice any patterns from the code above? It seems like we are simply repeating 2 lines of code over and over again depending on the number of sides the shape has. So does that mean for a shape with 8 sides we would have to write 16 lines of code? What about a shape with 36 sides? There must be a better way!

One way to simplify our code and to avoid repeating the same lines of code we could use a for loop which can repeat chunks of code for a certain number of times


import turtle as t

for i in range(4):
    t.forward(100)
    t.left(90)


import turtle as t

for i in range(3):
    t.forward(100)
    t.left(120)


While using the letter " i " in a for loop what is normally done you could use something else in its place. In this example, it may make more sense to use "sides" instead. Now if you go back to your code you could easily see that this loops based on a number of sides!


import turtle as t

for sides in range(3):
    t.forward(100)
    t.left(120)

Adding Color:


Let's spice thing us a bit and learn how we can add color to our turtle creation. Colors are strings so don't forget to add quotation marks around them! For a list of colors click here.


import turtle as t

t.color("blue")

for i in range(4):
    t.forward(100)
    t.left(90)



Filling in shapes:


Animation Speed:


Creating Patterns: