Variables
Introduction
Variables are containers used to store values. In Python, variables are defined using the assignment operator =. For example:
Variables can also be updated using the assignment operator:
The output is:
Assignment Operator
The syntax of the assignment statement is:
The assignment operator works from right to left. For example:
The output is:
Having a literal to the left of the assignment operator will result in an error:
This will throw the following error:
Dynamic Typing
Python supports dynamic typing. In a dynamically typed language, a variable is simply a value bound to a name; the value has a type — like int or str — but the variable itself doesn’t. For example:
The output is:
Referencing vs Defining
When a variable that has already been defined is used in an expression, we say that the variable is being referenced.
If a variable is referenced before it has been assigned a value, Python throws a NameError:
The output is:
Keywords and Naming Rules
Certain words in Python, called keywords, have special meanings. Examples include:
Keywords cannot be used as variable names:
In addition to this restriction, variable names in Python must follow these rules:
- A variable name can only contain alphanumeric characters and underscores:
a-z,A-Z,0-9,_ - A variable name must start with a letter or an underscore.
- Variable names are case-sensitive (
age,Age, andAGEare three different variables).
Reusing Variables
Variables can be used in computing the values of other variables. For example:
Multiple Assignment
You can assign values to multiple variables in one line:
Another way is to assign the same value to multiple variables:
Even though x, y, and z start off equal, the equality is broken if one of them is updated:
The output is:
Assignment Shortcuts
Python provides shorthand notations for arithmetic operations combined with assignment:
| Shortcut | Meaning |
|---|---|
x += a |
x = x + a |
x -= a |
x = x - a |
x *= a |
x = x * a |
x /= a |
x = x / a |
x %= a |
x = x % a |
x **= a |
x = x ** a |
For example:
The output is:
Deleting Variables
You can delete variables using the del keyword:
After the deletion, trying to access x will throw a NameError: