Variables are simply names with values assigned to them. Some examples:

a = 12
b = 15
z = "a string"

Variables can be used in expressions. When the expression is executed, each variable is substituted by the value they stand for:

>>> a * b
180

In Python, everything is an object. The following assignment ‘restarts’ the variable named a, connecting it to another object:

>>> a = a + 10
>>> a
22

Naming variables

Variable names can’t start with a number. If you try it, a SyntaxError will be raised:

>>> 1a = 12
Traceback (most recent call last):
  File "<stdin>", line 1
    1a = 12
     ^
SyntaxError: invalid syntax

Variable names can contain numbers, as long as they are not the first character:

a1 = 12

Underscores are also allowed in variable names — and have a special meaning too, indicating private names (more about this later):

_a = 12
a_ = 13

Variable names are case sensitive. So x is a different variable than X:

>>> x = 12
>>> X = 13
>>> x, X, x == X
(12, 13, False)

Therefore, this will raise a NameError:

>>> y = 102
>>> Y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Y' is not defined

Assigning multiple items

When declaring variables, it is possible to assign several items at once:

x, y, z = 0, 100, 200

This only works if the number of variables and the number of values are the same:

>>> x, y, z = 0, 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)

If two or more variables have the same value, they can be assigned at once:

>>> x = y = z = 100
>>> x, y, z
(100, 100, 100)

Swapping values

In Python, we can swap the values of two variables at once with the following syntax:

>>> a, b = 10, 20
>>> a, b = b, a
>>> a, b
(20, 10)
Last edited on 01/09/2021