Understanding the Basic Assignment Operator (=)
We’ve already used the equal sign (=) multiple times. It assigns the value on the right-hand side to the variable on the left.
Example:
python
CopyEdit
x = 10
This means the value 10 is now stored in the variable x.
But what if you want to add something to x or multiply it without writing x = x + 3? That’s where Python’s compound assignment operators come into play.
Common Python Assignment Operators
Let’s go through the most commonly used assignment operators with examples:
| Operator | Description | Example | Equivalent To |
|---|---|---|---|
| = | Assign | x = 5 | – |
| += | Add and assign | x += 3 | x = x + 3 |
| -= | Subtract and assign | x -= 2 | x = x - 2 |
| *= | Multiply and assign | x *= 4 | x = x * 4 |
| /= | Divide and assign | x /= 2 | x = x / 2 |
| //= | Floor divide and assign | x //= 3 | x = x // 3 |
| %= | Modulus and assign | x %= 3 | x = x % 3 |
| **= | Exponent and assign | x **= 2 | x = x ** 2 |
These operators help you write cleaner and more efficient code.
Real-Life Example: Cutting a Metal Strip
Let’s say you have a metal strip of a certain length and want to divide it into pieces of 5 meters and 3 meters. You also want to calculate how much strip is wasted.
Sample Program
python
copyEdit
Code Explanation (Line-by-Line)
- strip_length = int(input(...)): Takes user input and converts it into an integer.
- p5 = strip_length // 5: Calculates how many 5-meter pieces can be made.
- strip_length %= 5: Updates the strip_length to what's left after 5-meter cuts.
- a / b → Performs normal division (returns float)
- p3 = strip_length // 3: Determines how many 3-meter pieces can be made from the remaining strip.
- strip_length %= 3: Calculates the final leftover — the wastage.
- print(...): Displays the results.
Output
text
CopyEdit
Enter the total length of the metal strip: 54
Number of 5-meter pieces: 10
Multiplication: 60
Number of 3-meter pieces: 1
Wastage (in meters): 1
Why Use Assignment Operators?
Assignment operators make your code:
- More concise: x += 1 is shorter than x = x + 1
- More readable: Clearly shows that you’re updating a variable in place
- More maintainable: Easier to tweak values during testing and debugging
You'll frequently see these operators in loops, conditionals, counters, and real-world applications.
Watch the Full Lesson on YouTube
Want to see this example in action? Watch our full video breakdown with code execution, tips, and more: Watch on YouTube →
Final Thoughts
Assignment operators are fundamental tools in Python that simplify code and make it easier to write and maintain. Whether you're updating a value, performing calculations, or developing real-world logic like metal cutting, these operators save time and reduce errors. Keep practicing them — they’ll become second nature soon!