Variables are memory locations used to store values. They can be visualized as storage bins as shown in Figure 2.1. Each memory location has a unique memory address. Each address can store one item at a time.
Variable declaration is reserving a memory location for storing values. However, the declaration is not needed in Python. The variable is created the moment the first value is assigned to it.
Strings can also be assigned to a variable. For strings, either a single or double quote is needed.
A constant is a type of variable that holds values, which cannot be changed. In reality, we rarely use constants in Python. Constants are usually declared and assigned on a different module/file. Then, they are imported to the main file.
The name chosen for the variable should be short (easy to remember) and descriptive (understandable). Short names help the programmers easy to remember and result in more concise code. Descriptive names make it easier to understand their purpose as well.
Rules for naming variables in python are:
Good Programming Practice for naming variables:
Examples of valid Python variable names | ||
---|---|---|
total | interest | grossPay |
slope | computePay | density |
findMin | count | cha |
Examples of invalid Python variable names | |
---|---|
2AB3 | begins with a number |
E-6 | contains a special character |
for | this is a keyword |