Often we want to change the value of a variable. Maybe we are counting how many questions the player got right, so we need to add 1.
Or we want to multiply something by 10.
Traditionally, that would look like this:
score = score + 1
num = num * 10
But most modern programming languages have operators to do this with less typing.
1 2 3 4 5 6 7 8 9 10 11 |
|
a: 5 b: 5 c: 5 a: 9 b: 0 c: 30
The +=
operator adds to the variable on the left. -=
subtracts and *=
multiplies.
Python also has /=
, //=
, %=
and even **=
. For example:
x = 5
x **= 2
# x is now 25
If you know another programming language, you might be surprised that Python does not have ++
or --
. You will have to use x += 1
instead.
- Does
//=
work without importing future division? Add some code to try it out and then answer in a comment.
©2017 Graham Mitchell