Variables
A variable is a name bound to a value with = (assignment). Read x = 5 as "let the
name x refer to 5," not "x equals 5".
>>> price = 20
>>> quantity = 3
>>> total = price * quantity
>>> print(total)
60
A variable can be rebound, that is, it can be made to point to a different value, potentially of a different type.
>>> n = 10
>>> n = n + 1
>>> print(n)
11
>>> n = "now text"
>>> print(n)
now text
Right side first
In n = n + 1, Python evaluates n + 1 first, using the current value of n
then makes n refer to the result. That is, the right hand side of an assignment
statement is always evaluated first.
The value cannot be on the left-hand side of an assignment statement
The following is illegal in Python:
10 = n
The left-hand side of an assignment statement must always be an identifier, a.k.a variable name.
Naming rules & style
- use letters, digits, and underscores
- a variable name cannot start with a digit
- variable names are case-sensitive (
totalandTotalare different names) - style: lowercase
with_underscores - style: descriptive. Prefer
tax_rateovertr
Assignment shortcuts
Multiple assignments on one line:
>>> x, y = 1, 2
>>> a = b = 0
Update and rebind:
>>> count = 0
>>> count += 5
>>> count -= 2
>>> print(count)
3