Assignment operators are symbols that allow you to assign a value to a variable.
The most basic assignment operator is =
(equal sign).
It means:
"Put the value on the right into the variable on the left."
For example:
score = 100
But Python is not just limited to =
. It has more advanced assignment operators that perform both math operations and assigning values simultaneously. This makes your code shorter, cleaner, and easier to understand.
Compound Operators (Math + Assignment Together)
Let's go back to the game score example. Let's say you have this code:
score = 100
Now you want to add 50 to it.
(+= operator):
The +=
operator here is a shortcut that does both addition and assignment at the same time.
score = 100
score += 50 # This means: score = score + 50
print(score) # Output: 150
Complete List of Shortcut Operators
Here is a complete list of these handy shortcuts:
Operator | Example | Is the Same As... | Description |
---|---|---|---|
+= | x += 5 | x = x + 5 | Add and assign. |
-= | x -= 5 | x = x - 5 | Subtract and assign. |
*= | x *= 5 | x = x * 5 | Multiply and assign. |
/= | x /= 5 | x = x / 5 | Divide and assign (gives a float). |
//= | x //= 5 | x = x // 5 | Floor divide and assign. |
%= | x %= 5 | x = x % 5 | Find remainder and assign. |
**= | x **= 2 | x = x ** 2 | Raise to the power and assign. |
Why use these shortcut operators?
there are two big advantages:
- Clarity of Intent: When you write
score += 50
, it is clear that you are updating an existing value. This method shows that the value is being incremented, not that a new value is being given. - More Readable: When the program becomes larger, such short shortcut codes are easier to read and understand than repeated code.
Frequently Asked Questions (FAQs)
Q: Does the += operator work with strings?
A: Yes, it does! And it's very useful.
+=
works as a concatenation of strings. This is the easiest way to do it when you need to build a long message by adding parts together.
Example:
message = "Hello"
message += " World" # appends " World" to the end of the message
print(message) # Output: Hello World
Q: Is x += 1 faster to execute than x = x + 1?
A: In today's Python, when you're working with simple data types like numbers or strings, there's not much difference in speed.
In fact, the advantage of using +=
is that it makes your code shorter, cleaner, and easier to read. That's why people prefer it — not for performance, but for clarity.
Next Lesson: Comparison Operators (==, !=) in Python