Topic 2: Variables and Constants

Variables

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.

...
Figure 2.1

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.

Example: let's say you are creating your budget and need to store values in rent, food, travelling and then the total to store all the expenses. The code in figure 2.2 shows storing the values in the variables and displaying the total
  • ...
    Figure 2.2

Strings can also be assigned to a variable. For strings, either a single or double quote is needed.

Example
  • first_name = “John”
    second_name = ‘Ken’

Constant

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.

Variable Names

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:

  • Name can only begin with a letter or an underscore (_)
  • It can contain only letters, numbers, and the underscore character. No punctuation marks, spaces, or other special characters (such as $ or %) are allowed
  • Cannot be a keyword (a word that has special meaning in Python)
  • Names are case-sensitive. Example: discount is different from DISCOUNT and Discount

Good Programming Practice for naming variables:

  • Use uppercase letters for named constants and lowercase for variables. Example: PI (constant), radius (variable)
  • If constants contain more than one word, separate words with underscores. Example: TAX_RATE
  • If variables contain more than one word, capitalize the first letter of each word after the first (called camel case). Example: adjustedGrossIncome

Table 2.1
Examples of valid Python variable names
total interest grossPay
slope computePay density
findMin count cha

Table 2.2
Examples of invalid Python variable names
2AB3 begins with a number
E-6 contains a special character
for this is a keyword