In this lesson, you will learn how to use augmented assignment operators to update variable values more efficiently and cleanly.
The "Shorthand" Approach
When you are programming, you will often find yourself updating a variable by adding, subtracting, or modifying its current value. For example, if you are tracking a score in a game, you might write:
score = 10
score = score + 5
While this works perfectly, Python offers a "shorthand" way to write this. By using an augmented assignment operator, you can combine the arithmetic operation and the assignment into a single step. Instead of typing the variable name twice, you can use the += operator:
score = 10
score += 5
How It Works
When you use score += 5, Python performs the addition and updates the score variable automatically. This isn't just a stylistic choice; it makes your code much easier to read, especially when you have long variable names or complex operations.
This works for all standard mathematical operators:
+=(Addition):x += 5is the same asx = x + 5-=(Subtraction):x -= 2is the same asx = x - 2*=(Multiplication):x *= 3is the same asx = x * 3/=(Division):x /= 2is the same asx = x / 2%=(Modulo):x %= 3is the same asx = x % 3
Why Use Them?
Beyond just saving keystrokes, these operators make your intent clear. When another programmer sees counter += 1, they instantly know that you are incrementing an existing value rather than performing a complex calculation involving new data. It keeps your code tidy and reduces the risk of typos when repeating long variable names.
Remember, these operators update the variable in place. If you are working with immutable types like integers, Python creates a new object and updates the variable name to point to it, following the same assignment rules you have already learned.
Key Takeaway: Augmented assignment operators like += and -= allow you to update a variable's value concisely, making your code more readable and easier to maintain.