Assignment statements in Python are of this form:
variable =
expression
A simple example of an assignment statement is
“sum = 0
”, which associates the number 0 with
sum
.
Or “y = x + 2
”, which computes the sum of
x
's current value with 2 and associates the variable
y
with the result.
A variable is any word you make up, composed of
letters, digits, and underscores, provided it doesn't start with
a digit and it doesn't happen to
conflict with a short list of words special to Python (e.g., for
and if
).
An expression can be as simple as a number or a variable, or it can be built up using mathematical operators. Operators available to us include:
**
exponentiation *
multiplication /
division ( 16 / 6
is 2.667)%
remainder ( 16 % 6
is 4)//
integer division, ignoring remainder ( 16 // 6
is 2)+
addition -
subtraction
Operations are done in the same order of operations as in mathematics: Exponentiation comes first, followed by the different multiplication and division options, followed by addition and subtraction. As in mathematics, you can use parentheses to specify a different order. Here are some examples.
y = 2 * x ** 2 + 1
Let y be the result of 2 x² + 1 z = 1 / (y + 1)
Let z be the reciprocal of y + 1 w = 1 / y + 1
Let w be the result of adding 1 to the reciprocal of y u = x % 10
Let u be the ones' digit of x v = (x % 100) // 10
Let v be the tens' digit of x (Parentheses aren't necessary here, but it's easier to read.)
Finally, let me mention one hangup for many beginners. Consider this sequence.
a = 2
b = a + 1
a = 4
Obviously, the first statement puts 2 into a
,
and the second statement puts 3 into b
.
The third statement changes a
to 4;
but b
does not change.
The value of b
is still 3, and it won't change until
an explicit assignment to b
.