Variables

Introduction

Whew. Experimenting with the angles requires you to change three different places (numbers) in the code each time. Imagine you’d want to experiment with all of the squares’ sizes, or with with rectangles! Fortunately there are easier ways to do so than changing lots of numbers every time.

This is where variables come into play: You can tell Python that from now on, whenever you refer to a variable, you actually mean something else. That concept might be familiar from symbolic maths, where you would write: Let x be 5. Then x * 2 will obviously be 10.

In Python syntax, that very statement translates to:

x = 5

After that statement, if you do print(x), it will actually output its value — 5. Well, can use that for your turtle too:

turtle.forward(x)

Variables can store all sorts of things, not just numbers. A typical other thing you want to have stored often is a string - a piece of text. Strings are indicated with a starting and ending " (double quote). You’ll learn about this and other types of data you can store, and what you can do with them later on.

You can even use a variable to refer to the turtle by a name:

timmy = turtle

Now every time you type timmy python knows you mean turtle. You can still continue to use turtle as well:

timmy.forward(50)
timmy.left(90)
turtle.forward(50)

A variable called angle

Exercise

If we make a variable called tilt (we could assign it a number of degrees), how could we use that to experiment much faster with our tilted squares program?

Solution

tilt = 20

turtle.left(tilt)

turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)

turtle.left(tilt)

... and so on!

Bonus

Can you apply that principle to the size of the squares, too?

The house of santa claus

Exercise

Draw a house.

_images/house.png

Hint

You can calculate the length of the diagonal line with the Pythagorean theorem. That value is a good candidate to store in a variable. To calculate the square root of a number in Python, you’ll need to import the math module and use the math.sqrt() function. Exponentiating a number is done with the ** operator (so squaring means ** 2):

import math

c = math.sqrt(a**2 + b**2)