More Assignment Operators
There are a few miscellaneous operators that are useful. We call them Compound Assignment Operators.
Compound Assignment Operators¶
Operators | Function |
---|---|
+= |
Adds to a variable |
-= |
Subtract to a variable |
*= |
Multiply into a variable |
/= |
Divide into a variable |
Adding into a variable +=
¶
We can add a number to a variable like this:
1 2 3 4 5 6 7 |
|
And we can use a shortcut Compound Assignment Operator too. Since this is less typing we have fewer chances of making an error. Also, this is the way you will see professional programmers do it.
1 2 3 4 5 6 7 |
|
Subtracting into a variable -=
¶
We can subtract a number from a variable like this:
1 2 3 4 5 6 7 |
|
And we can use a shortcut Compound Assignment Operator too. Since this is less typing we have fewer chances of making an error. Just like with addition, this is the way you will see professional programmers do it.
1 2 3 4 5 6 7 |
|
Multiplying into a variable *=
¶
As you might now guess, we can also multiply into a variable like this:
1 2 3 4 5 6 7 |
|
This works too and it the preferred way to do it:
1 2 3 4 5 6 7 |
|
Dividing into a variable /=
¶
I think you could figure out that this one was coming! Dividing like this:
1 2 3 4 5 6 7 |
|
But, dividing like this is better:
1 2 3 4 5 6 7 |
|
Labs
- Lab09: Compound Assignment Operators
- unit02/labs/lab-09-compoundAssignmentOperators.html
Exercises
- Exercise for lab09
- unit02/exercises/exercise-09.html