|

# How To Use Variables In Python Turtle

We’re having some fun drawing different shapes with the Python Turtle library, but we can make the functions that draw those shapes more interesting by incorporating variables into the programs. By using a variable when drawing a square, for example, we can control how far the turtle moves when making a line for each side of the square. This way, we can use one function that can draw any size square we like by making use of a variable. Let’s see how to do that now.

## Adding A Variable To draw_square()

This new draw_square() function now has a new variable named length.

``````def draw_square(length):
for i in range(4):
forward(length)
left(90)``````

This makes it possible to pass in a number value when calling the draw_square() function so that each side can move forward by that amount when drawing the square. We can test this out by calling draw_square() and passing in 75, which makes the turtle move 75 pixels.

``````from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('arrow')

def draw_square(length):
for i in range(4):
forward(length)
left(90)

draw_square(75)
done()``````

## Drawing Different Sized Squares

Now that a variable is in use, we can easily draw squares of different sizes. Let’s test out drawing a square that has 150 pixels for each side.

``draw_square(150)``

Using a variable when defining a function makes the function more flexible since can change the output the function creates without having to update the function itself every time.

## Setting A length default

If the draw_square() function is called without passing in a value for the length variable, we will get an error.

```Traceback (most recent call last):
File "C:\python\justhacking\testing.py", line 14, in <module>
draw_square()
TypeError: draw_square() missing 1 required positional argument: 'length'```

To avoid this possible error condition, let’s redefine the draw_square() function and make use of a default value if one is not provided. We’ll set the default to 90 like so.

``````from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('arrow')

def draw_square(length=90):
for i in range(4):
forward(length)
left(90)

draw_square()
done()``````

Now when draw_square() is called, no error is displayed and the program simply defaults to drawing a square that has a length of 90 pixels for each side. The program below calls the draw_square() function 3 times. Once with no variable passed to it, and twice with two different number values.

``````from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('arrow')

def draw_square(length=90):
for i in range(4):
forward(length)
left(90)

draw_square()
draw_square(150)
draw_square(200)
done()``````

The result is three squares with three different sizes.

|