- By Rob Miles
Variables in Python
We’ve seen how Python lets us work with numbers and text. We can use Python as a calculator; we can type calculations as expressions, and Python will evaluate them and display the result. A calculator usually has a memory function that you can use to avoid typing in the same value repeatedly. You can store a frequently used value or a running total in memory and recall it with the touch of a button.
A variable is how we add memory to our Python programs. You can think of a variable as a storage location you can refer to by name. You create a variable in a Python program by thinking of a name for the variable and then putting a value in the variable.
total = 0
This Python statement creates a variable with the name total. This variable could be used to hold the total of a sequence of numbers. When Python sees the word total in the program, it fetches the contents of the variable called total.
The statement above is called an assignment, which is not a piece of homework (thankfully); instead, it’s the act of assigning one thing to another. Figure 4-1 shows the anatomy of an assignment statement like this.
Figure 4-1 Anatomy of an assignment statement
The box on the left of the assignment shows the variable to be assigned. The symbol in the middle is the equals operator, which means “assignment.” The box on the right is an expression, which gives the value to be assigned. The expression can be as complicated as you like.
total = us_sales + world_wide_sales
This statement would set the value of the variable total to the result of adding the contents of the variable us_sales to the contents of the variable world_wide_sales.
This sequence of actions has performed some simple data processing. The data going into the process was the value in the variable total, which emerged from the process with its value increased by 10.
We used the name total for the first variable that we created. When you write a program, you must come up with names for the variables in that program. Python has rules about the way you can form names:
A name must start with a letter or the underscore character (_) and can contain letters, numerals (digits), or the underscore character.
The name total is a perfectly legal name for a variable, as is the name xyz. However, the variable 2_be_or_not_2_be would be rejected with an error, because it starts with a numeral instead of a letter or the underscore character. Also, Python views uppercase and lowercase letters differently; for example, FRED is regarded by Python as a different name from fred.
Python allows names of any length, and the length of a variable name does not affect the speed of the program, meaning longer variable names don’t slow down the program. However, very long names can be a bit hard to read, so you should try to keep them down to the lengths shown in the examples.