Variables
Introduction
One of the most common elements we make use of when writing code is the variable. Variables are named placeholders for values which can change. Wikipedia defines a variable as follows:
"a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value. The variable name is the usual way to reference the stored value; this separation of name and content allows the name to be used independently of the exact information it represents." (http://en.wikipedia.org/wiki/Variable_(computer_science))
Why do we need variables?
The reason variables are important, is because we do not always know what values we will be dealing with. For example, imagine you want to create a simple program which reads in two numbers from the user and add them together. You do not know in advance what the two numbers are that the user is going to enter, so you need to use named placeholders to represent these two values, which we can then add together.
Alegraic Variables
In Algebra, we use variables extensively to either represent unknown values, or to show that a certain mathematical relationship always holds true. As an example, we might have a mathematical statement which says:
2x + 1 = 9
In this statement, the x is the variable, or unknown. In the statement above, we can easily solve for x and determine it's value is 4. In a computer program, we might have a similar situation, such as:
x = 4
print (2 * x) + 1
Output: 9
Note: Try this for yourself. Open up the command line, and enter the Python interactive interpreter by typing "python" and pressing Enter. Then type "x = 4" and Enter, then "print (2 * x) + 1" and press Enter. You will see on the next line "9" will be outputted.
What is a variable?
Let's take a moment to understand what a variable is in relation to what we learned in the previous section on "Computer Architecture".
When the python interpreter sees us using a new variable (In the above example it was "x"), it realizes that it needs to store a value in memory. This value in memory will be of a certain type, such as a number, or a string of characters, or a date, and so on. An available block of memory is then found, and the address of that memory where the value will be stored is then linked or associated to the name we have given the variable, called the "identifier".
From the above explanation, we see that a variable is made up of the following parts:
- Identifier: The name of the variable
- Pointer: The address in memory
- Value: The data being stored for the variable in memory
- Data Type: The type of data being stored
To understand these parts a bit better, let us try an example. Open up the Python interactive interpreter once more, and type out the following code:
x = 4
id(x)
In the above example, the "Identifier" is "x", but what is the pointer? Once you have entered "id(x)", a long number will appear. This long number is the pointer value, or the address of the location in memory where the value "4" is being kept.
So now we know the identifier, pointer and value. All that is left is to determine the Data Type. How do we do this? We use a function called type() as follows:
type(x)
Output:
So, from the output we see that the type is 'int', which stands for Integer. For those who are a bit rusty when it comes to Mathematics, an "Integer" is a whole number (so a number that has no decimal point). Examples of integers are: 1, 100, 30, 5, 3000000. Examples of numbers that are not integers are: 1.5, 0.001, 6000.55. We will learn more about different data types in a future section.
Now that we understand the terminology of identifiers, pointers, values and data types, let us now put together a more technical definition of a variable using this terminology:
Technical Definition: A variable is an identifier which points to a value of a certain data type stored at a specific location in memory.
Using Variables
Creating Variables
In a lot of programming languages, variables first have to be initialized with a certain data type before they can be used. Fortunately for us, we don't have to worry about this when using Python, as Python flexibly selects the appropriate data type for the value depending on how you are making use of the variable.
Creating a variable in Python is very easy. We simply need to pick a name (identifier) for the variable, and then give it a value by using the equals ("=") sign. Here are some examples:
birth_day = "1985-12-21"
name = "Ralfe Poisson"
cur_age = 27
this_course_id = 1079
Some rules for choosing a name/identifier for the variable:
- The name you choose should be descriptive of what you are using the variable to store.
- The variable name should not contain spaces
- Avoid using special characters, such as $, %, (, !. Note the underscore character is allowed, and is a great way to separate words in the variable name (E.g.: "cur_age").
Printing Variables to the screen
If we simply want to print out the value of a variable, we use the print function follwed by the identifier, as such:
my_number = 1
print my_number
Output: 1
However, if you want to print out some text with the value of the variable contained within the text, we do so as follows:
first_name = "Bob"
print "Hello, my name is %s" % (first_name)
Output: Hello, my name is Bob
Note here that "%s" is used as a place holder for the value of the variable. To include multiple variables in the output text, we simply list the variables in order, separated by commas like this:
first_name = "Billy"
middle_name = "Bob"
last_name = "Thornton"
print "Hello, my full name is %s %s %s" % (first_name, middle_name, last_name)
Output: Hello, my full name is Billy Bob Thornton
Variables in Calculations
Just as we use variables in Mathematics, so too can we make use of variables in calculations when writing code in the same way. Let's have a look at an analogy:
y = f(x) = 2x + 1
f(4) = 2 * 4 + 1
f(4) = 9
x = 4
y = 2 * x + 1
print y
Output: 9
Variables to store user input
Often, when writing software to run on the command line, you need to read in user input. One method for doing so is by reading keyboard input. To read in keyboard input, we can use the raw_input() function, like this:
name = raw_input("What is your name? ")
print "Hello, %s" % (name)
The raw_input() function will display "What is your name? " on the command line, and waits for the user to type in some input. When the Enter key is pressed, the user input is then returned and stored in the name variable.
Note: If you see an error that looks like "TypeError: cannot concatenate 'str' and 'int' objects", you will need to convert the text input from the user into a number using the int() function. Here is an example bellow:
a = raw_input("Please enter a number? ")
a = int(a)
answer = a * 2
print "%d * 2 = %d" % (a, answer)
A note on Terminology
Whilst working with variables, you might encounter terms such as "constants" and "literals". Let's take a quick look at what these refer to.
Constant A constant is a variable whose value remains unchanged (constant) throughout the execution of the program. Some examples of constants would be the current version number of the program, the directory path where the program was run from, and so on.
Literal A literal is basically a value. For example, a String literal is "Hello", or an integer literal could be 3. It is important to understand the difference between a variable and a literal. A variable stores values in memory, whereas a literal is itself a value. Let us consider an example for clarity:
name = "Matthew"
print "Hello, my name is %s" % (name)
In the above example, "name" is a variable, where as "Hello, my name is" is a string literal to which the variable's value was appended for printing to the screen.
Examples
Here are some examples of lines of code making use of variables in different ways.
Division Example:
a = 10
b = 20
answer = b / a
print "%d / %d = %d" % (b, a, answer)
Output: 20 / 10 = 2
Addition Example:
a = 10
b = 5
answer = a + b
print "%d + %d = %d" % (a, b, answer)
Output: 10 + 5 = 15
String
colour = raw_input("What is your favourite colour? ")
print "I like %s too!" % (colour)
Exercises
- Write a small program to read in two numbers from the command line, add them together and print out the answer.
- Write some code to ask for the user's first pet's name, and the make of their first car. Then inform them of their "stage name" which is a combination of the pet's name and the make of car.