What Are Assignment Operators?
In Python, assignment operators are used to assign values to variables. They bind a value to a name so you can use it later in your code. Python supports basic assignment and compound assignment operators that both assign and update values.
1. Basic Assignment Operator
The single equals sign = assigns a value to a variable.
Here, x gets 10 and y gets 5.
2. Compound Assignment Operators
Compound assignment operators update a variable’s value based on its current value and an expression.
Addition Assignment +=
It is equivalent to:
Subtraction Assignment -=
Equivalent to:
Multiplication Assignment *=
Equivalent to:
Division Assignment /=
Division always returns a float result.
Floor Division Assignment //=
This performs integer (floor) division and assigns the integer result.
Modulus Assignment %=
The variable becomes the remainder of the division.
Exponentiation Assignment **=
Raises x to the power of 3.
Why Use Compound Assignment?
Compound assignment operators:
Make code shorter
Improve readability
Avoid repeating the variable name
Example:
Assignment with Different Types
You can assign different data types to variables in Python because it is dynamically typed.
Chain Assignment
Python allows assigning the same value to multiple variables in one line.
Key Points to Remember
=assigns values to variablesCompound operators like
+=,-=, etc. update the variable’s existing valuePython supports dynamic typing (variables can change data types)
Chain assignment assigns one value to multiple variables