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


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)


Adding Color:


Let's spice thing us a bit and learn how we can add color to our turtle creation


import turtle as t

t.color("blue")

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