1: Variables

Variables act as "storage locations" for data in a program. They are a way of naming information for later usage. Each variable has a name; an example variable name we will use is myLuckyNumber. To store information in a variable, we write a command using an equal sign in the following way:

«the variable name» = «the value you want to store»
(We use «double angle brackets» in our lessons, like above, to indicate special parts of expressions.) For example, the Python line

myLuckyNumber = 13
stores the value 13 in the variable myLuckyNumber. Then, anywhere you write the variable name myLuckyNumber again, Python retrieves the stored value. Below, there is a short example of using variables. It has more than one line of instructions: Python executes the first line, then the second line, and so forth until it reaches the last line. Press the Run program button to see what it does.
Example of using a variable.
Look at the 5 lines of the program in order, and how they correspond to the output. As you can see, myLuckyNumber keeps its value of 13 for the first two print statements, then its value is changed to 7. We also introduced the plus operator (+) above, which adds two numbers together. Similarly, there are operators for subtraction (-), multiplication (*), and division (/). We'll return to these in a later lesson. You can simulate the memory storage of a computer with paper and pencil, by keeping track of the values in a table. Here is an example; remember that * means multiplication in Python.

Goal: determine the final values of all variables at the end of the program.

first = 2
second = 3
third = first * second
second = third - first
first = first + second + third
third = second * first
Idea: We use a table to keep track of the values as they change. Scroll to the bottom to see the final answer.

Statement Values after statement executes
first second third
first = 2 2
second = 3 2 3
third = first * second 2 3 6
second = third - first 2 3 4 6
first = first + second + third 2 12 4 6
third = second * first 12 4 6 48

Thus at the end of the program, the value of first is 12, the value of second is 4, and the value of third is 48.

Drawing a table like this on pencil and paper is always a good idea and helpful when understanding or fixing code. We also have an automated Python3 visualization tool to virtually execute programs like this one step at a time (see also the link in the top menu). Here's what it looks like when we run the same program on the visualizer. Use the Forward > button or press the arrow key on your keyboard to step forward (or back). Note how the variables change as each line executes. Here is a short answer exercise about variables.

Short Answer Exercise: x Marks the Spot
What is the value of x after these commands execute?

x = 10
x = x + x
x = x - 5

Two Common Errors

If you ask Python about a variable that has not been defined, you get an error.

Example: An Undefined Variable
As you can see, we get an error message saying NameError: name 'trouble' is not defined. Sometimes you can get errors like this from simple typos: if you define a variable address=32, then try to print(adress), the same type of error occurs. Another error has to do with accidentally swapping the sides of an = statement.
Example: SyntaxError: can't assign to literal
The first line is fine but the second line causes an error: Python thinks the second line 4 = x is trying to change the value of 4, but you are only allowed to change the values of variables, and 4 is not a variable. While A = B and B = A are the same in mathematics, they are different in programming.


This is a warm-up to get you started with variables.

Coding Exercise: Heads, Shoulders, Knees and Toes
Write a code fragment (a short part of a Python program) to count heads, shoulders, knees, and toes at a party. The grader will automatically define a variable people for you, counting the number of people at the party. Your code must define four variables, one called heads, one called shoulders, one called knees, and one called toes, equal to the number of heads, shoulders, knees, and toes in total at the party. Your program does not need to print any output. The grader will select a new random value for people each time your code runs.
Click here if you want a hint on getting started

Code Scramble

The next item in this lesson is a new type of programming exercise, where you don't have to do any programming. We will provide you with a correct program, but the catch is that its lines have been put into a scrambled-up order. Your job is to drag-and-drop the lines to rearrange them into a correct program.

Scramble Exercise: Speed Calculator
You are in a bike race which goes up and down a hill. The grader will pre-define four variables for you: uphillDistance and downhillDistance give the distance (in km) of both parts of the race, and uphillTime and downhillTime give the time (in minutes) of how long it took you to complete each part of the race. Write a program that will print out your average speed (in km/min) for the entire race.
Drag and drop with your mouse to rearrange the lines.
Click for a hint if you're stuck 
  • totalDistance = uphillDistance + downhillDistance
  • print(averageSpeed)
  • averageSpeed = totalDistance / totalTime
  • totalTime = uphillTime + downhillTime

Exchange Program

Here is the last exercise in this lesson.

Coding Exercise: Exchange Program
Write a program to swap the values of two variables. The grader will automatically define variables x and y for you, with numerical values. You must write code that exchanges their values: the value of x after your code runs must equal the value that y had before your code ran, and the value of y after your code runs must equal the value that x had before your code ran. Your program does not need to print any output.
The most common solution is short, but can be hard to find. Click on each hint if you want to read it. 
Hint, part 1
You do not need to use any arithmetic (+-*/) to solve this problem. You only need to use variables and =. You can define new variables with any name, if you need to.
Hint, part 2
We have two goals: put the original value of y into x, and put the original value of x into y. If all we wanted to do was the first goal (in other words, if we only wanted to put the value of y into x), we could use the one-line program

x = y
How can we do both goals at once?
Hint, part 3
The following program might seem promising,

x = y
y = x
But there is a problem. For example, let's say that the grader starts by defining x equal to 10 and y equal to 99. If we run the two-line program above, after the first line both x and y will equal 99. The second line has no effect. You can try submitting this solution to the grader to check for yourself what happens. How can we keep the original value of x somewhere, in order to put it into y later?
Hint, part 4
Your first line should be something like xOriginal = x, to store the original value of x for later. Then you can set x = y. Finally, set y equal to the original value of x.
Hint, part 5
Click to read a wikipedia page giving pseudocode (in a different language) for swapping. Here is a link to a second method that uses arithmetic in a sneaky way, but it will only work with numbers and not with text.
Once you get this exercise correct, you are ready to move on to the next lesson. Click the Next button below.