In Python, assignment operators are used to assign values to variables. The most basic one is the simple =, but Python also provides compound assignment operators like +=, -=, *=, and others that combine arithmetic with assignment — making your code shorter and cleaner.
Basic Assignment (=)
x =5print(x)
Explanation:
This assigns the value 5 to the variable x.
Example in Machine Learning:
You might initialize model parameters or weights:
weight =0.01
Example in Game Development:
Setting the player’s initial health:
player_health =100
Add and Assign (+=)
x =5x +=3# same as x = x + 3print(x)# Output: 8
Explanation:
Adds 3 to the current value of x.
Example in ML:
Adding the batch loss to total training loss:
Example in Web Analytics:
Incrementing total website visits:
3. Subtract and Assign (-=)
Explanation:
Subtracts 4 from the current value of x.
Example in ML:
Gradient Descent weight update:
Example in Game Development:
Reducing player health after damage:
4. Multiply and Assign (*=)
Explanation:
Multiplies the current value by 3.
Example in ML:
Scaling normalized inputs:
Example in E-commerce:
Calculating total cost after multiple items:
5. Divide and Assign (/=)
Explanation:
Divides the current value by 4.
Example in ML:
Averaging loss across batches:
Example in Finance:
Calculating average monthly spending:
6. Modulus and Assign (%=)
Explanation:
Stores the remainder of x ÷ 3.
Example in ML/Logging:
Printing logs every few iterations:
Example in Gaming:
Cycle through turns:
7. Exponent and Assign (=)**
Explanation:
Raises x to the power of 3.
Example in ML:
Simulating learning rate decay:
Example in Physics Simulation:
Increasing speed exponentially:
8. Floor Divide and Assign (//=)
Explanation:
Performs integer division (no remainder).
Example in ML:
Determining number of batches:
Example in App Development:
Calculating pagination pages:
Summary Table
Operator
Description
Example (x = 5)
Result (x)
=
Assign
x = 5
5
+=
Add and assign
x += 3
8
-=
Subtract and assign
x -= 2
3
*=
Multiply and assign
x *= 4
20
/=
Divide and assign
x /= 5
1.0
%=
Modulus and assign
x %= 3
2
**=
Exponent and assign
x **= 2
25
//=
Floor divide and assign
x //= 2
2
Video Tutorial
Support Our Work
If you find this post helpful and would like to support my work, you can send a donation via TRC-20 (USDT). Your contributions help us keep creating and sharing more valuable content.