Chapter 3 (Variables and Assignments)
Let's go back to maths. In algebra, x is used as a representation of a number. If I let x = 33241, it follows that 3 x = 99723, x + 1 = 33242, without me needing to write the original number again. Since the value of x can vary, we call it a variable.
Most languages (including Python) have variables at their core. In Python, you can imagine the variable as a labelled box storing a value. You can replace the value in the box at any time. For the example of x = 3, you can visualize it like so:

Variables consist of two important parts: the name and the value.
Variable Name
Unlike in maths:
* Variable names must be unique (there are minor exceptions)
* Variable names can be more than a letter. "score", "camel_1" and "x" are all valid variable names
* Variable names CANNOT start with a number or symbol. "123_o" and "$" are not allowed
* Variable names CANNOT be special names used in Python. For example, since print() is a Python function, "print" is not a valid name. However, "print_1" and other names that do not match exactly are allowed
* Variables are case sensitive. That is, "variable_x" is different from "Variable_x" which is in turn also different from "variable_X".
Conventionally, * Variables are written with short, meaningful names * Variables are named with lowercase letters, using underscores in place of spaces
Variable Value
Unlike in maths: * Variables need not represent numbers. You can store other things in variables, like letters/words (known as strings) (Chapter 4), functions (Chapter 7), or lists (Chapter 8)
To define a variable with name "var_1" and value of 2.5,
Now, we can check the value of the variables var_1:
We can reassign the value of var_1 to an integer:
We can also define a variable using an existing variable:
We can even change a variable using itself:
There are other assignment operators which act as shortcuts for these cases:
| Statement | Equivalent Statement (using Assignment Operators) |
|---|---|
| var = var + 1 | var += 1 |
| var = var - 1 | var -= 1 |
| var = var * 10 | var *= 10 |
| var = var / 15 | var /= 15 |
| var = var % 2 | var %= 2 |