Variables

A variable is like a box. The box contains the value of a literal that is placed in it using the assignment operator (=). Variables are essential for every realistic Python program and take some time to understand if this is the first time you have used them.

Variables are created when they are first assigned. This statement:

a = 9

Is just like doing this:

A value in a box

The literal value 9 is placed in a box called a. Variables can be used anywhere in a program where you would use a literal (including some surprising places, but we’ll talk about that later). Copy this python code into the next cell and run it:

a = 9
print(a)
[ ]:

Notice how ``a`` is now a stand-in for the number ``9``?

Variable Assignment and Usage

When you assign a variable for the first time the variable name is created. In Python there’s no need to declare a variable in advance. Running the code in the cell below creates a variable named foo.

foo = 'The contents of foo'

The assignment operator (=) places a new value into a variable. Unlike mathematical expressions, which state something that’s true for all time, variable assignment changes the contents of the variable. Variables often will have a succession of different values inside of them during the execution of a program. Copy the code example into the next cell:

[ ]:

Executing the statement produces no output, but it creates the variable foo. Once created the variable can be used in any place that expects a value. For example:

print("foo is:", foo)

Copy the print statement into the next cell.

[ ]:

Try changing the literal on the right side of the equal sign and rerunning the cells in this section.

Watch out! Variables have to be assigned before they can be used.

Try this:

print(some_variable_not_here)
[ ]:

Variable Names

Variables can only have certain characters in their name to avoid confusion with Python syntax such as operators. There are a few rules to remember when you name your variables:

  1. A variable name must start with a letter or the underscore (_) character (no numbers).

  2. A variable name can only contain alpha-numeric characters and underscores (A-Z, a-z, 0-9, and _ )

  3. Variable names are case-sensitive (age, Age and AGE are three different variables)

The best thing to do is to name your variables descriptively, so that you know what they’re used for. For example:

length = 100
tu.draw(length)

Sometimes, it’s handy to shorten variable names so you can go quicker:

l = 100
tu.draw(l)

That can be confusing if it’s not extremely obvious what the variable l is for. If in doubt, you can be as verbose as you like. The underscore _ character means you can have very descriptive variable names. For example:

length_of_side = 100
tu.draw(length_of_side)

What style you choose is up to you. Just remember, you are the programmer who is most likely to be confused by your code.

Variables to Hold Constants

A good use of variables is to avoid repitition of constants in your program. Here’s an example of a program that has hard-coded constants, integers that control the shape.

tu = Turtle()
display(tu)
tu.draw(80)
tu.turn(120)
tu.draw(80)
tu.turn(120)
tu.draw(80)

If you wanted to draw a bigger or smaller triangle you would have to change all thre instances of the number 80. That’s boring and accident prone (what if you forget one?). A better program would use a variable instead. Enter this program into the next cell and run it:

from p4e.drawing import Turtle
tu = Turtle()
display(tu)

length = 80
angle = 120

tu.draw(length)
tu.turn(angle)
tu.draw(length)
tu.turn(angle)
tu.draw(length)
[ ]:

Try changing the value of the length and angle variables. What happens?

Updating and Changing Variables

A variable is just a way to get Python to remember a value for you. You can use or change the remembered value at any time. That means that when you read code you should watch for assignments and remember the new value of a variable in your program. With some practice you can do it with ease. However, right now it’s probably pretty confusing. Here’s an example program where the value of a changes a few times:

a = 10
a = a + 100
a = a * 2
a = a - 50
print(a)

Can you see how a changes from line to line? Enter the program into the next cell and execute it. Did you guess right?

[ ]:

Now let’s do something really cool. The previous example is pretty simple, so you might be easily able to track the changing value of a. Don’t worry if you are having trouble because the debugger can do it for you! Enable debugging using the switch next to the bug in the upper right of this tab. Set a breakpoint on line 1 and step through the program.

Data Types

Variables are how programs use the computer’s RAM memory. Each variable is held in a location in memory and the location is associated with the type of data that’s there. In many programming languages variables must only contain one type of value. For example, an integer or a string. In Python variables take any type of value depending on what they’re assigned. Python is dynamically typed, meaning that variables can have any type and that type can change. That means a programmer has to be careful. Mixing variable types when performing operations is usually not allowed. The type() function shows you the type of a variable or literal. Enter this program into the next cell and run it:

print("The type of 10 is", type(10))
print("The type of 10.5 is", type(10.5))
print("The type of 'Python' is:", type('Python'))
[ ]:

Now let’s update the program to use a variable instead of literals:

a = 10
print("The type of a is", type(a))
a = 10.5
print("The type of a is", type(a))
a = 'Python'
print("The type of a is", type(a))

Does the cell print what you expect?

[ ]:

Try executing the cell in the debugger. In the VARIABLES pane notice that the type of the variable is visible to you if you flip the switch to the table view.

Variables are Fantastic!

Variables can be put in your program anywhere a value is needed. You can do math on them, use them as the arguments to functions and a whole lot more (for example tu is a variable). Given the Python you’ve learned so far, it may be hard to see how powerful variables are but as we go you’ll use them more and more. Variables let you parameterize code in a way that makes your program interesting and useful. In the example below the size variable adjusts the size of the hexagon. Run the code in the cell, you won’t see a hexagon right away:

[ ]:
from ipywidgets import interact
from p4e.drawing import Turtle

tu = Turtle()
display(tu)

def hexagon(size):
    tu.clear()
    for _ in range(6):
        tu.draw(size)
        tu.turn(60)

Now run this cell and control the size of the hexagon!

[ ]:
interact(hexagon, size=50)