A variable is a named storage location that holds a single value.
- A variable's value must be stored in the computer's memory.
- There are different types of values.
Usually the characters that may be used in a variable name are restricted.
Typical allowable characters are: a-z, A-Z, 0-9, and _ (underscore), and a name cannot begin with 0-9.
The space character is a separator and so variable names cannot contain the space character.
There are two common schemes for joining multiple words to form a variable name:
- Underscore: last_name, date_of_birth
- Camel Case: lastName, dateOfBirth
Good Variable Names
Each variable should be given a name that describes the value it stores.
For example: average, taco_count, and first_name
Using good variable names helps immensely in the undertanding of what the code it is part of does.
Avoid single letter variable names.
Many programmers use i, j, and k, for counter or index variables.
I recommend using descriptive names for counter and index variables.
An instruction that gives a variable a value is called assignment.
Assignment in pseudocode:
- Replace the value in box A with one more than the value currently in box A
- Add one to A's value
- Set A to A + 1
This is more concise in Python, and in many programming languages.
A = A + 1
The expression on the right of the = is evaluated and the result becomes the variable on the left side of the = a new value. The variable on the left's old value is discarded.
An assignment instruction looks like an equation in algebra however it is completely different.
Clearly the following cannot be a valid algebraic equation:
A = A + 1
Some languages have used symbols other than =, for example <- to look like an arrow:
A <- A + 1
The = symbol is used in Python, and many programming languages for assignment.
Again, in assignment the expression on the right of the = is evaluated and the result becomes the variable on the left side of the = a new value. The variable on the left's old value is discarded.