Assignment operators in Python allow us to assign values to variables.
The most common assignment operator is the =
operator. This operator is used to assign the value on the right to the variable on the left.
In addition to the basic assignment operator (=
), there are compound assignment operators that combine an arithmetic operation with assignment, simplifying and optimizing the code.
If you want to learn more about Assignment Operators
check the Introduction to Programming Course read more
Basic assignment operator (=)
The basic assignment operator (=
) is used to assign a value to a variable. For example:
number = 10
In this example, number
is a variable that is assigned the value 10
.
The assignment operator is also used to update the value of a variable. For example:
a = 5; # Initial assignment
a = 10; # Updating the value
Compound assignment operators
+= operator
The +=
operator is used to add the value on the right to the variable and assign the result to the variable.
counter = 5
counter += 3 # Equivalent to counter = counter + 3
After this operation, counter
will be equal to 8
.
-= operator
The -=
operator is used to subtract the value on the right from the variable and assign the result to the variable.
total = 100
discount = 20
total -= discount # Equivalent to total = total - discount
After this operation, total
will be equal to 80
.
*= and /= operators
These operators are used to multiply (*=
) and divide (/=
) the variable by the value on the right and assign the result to the variable, respectively.
amount = 5
amount *= 2 # Equivalent to amount = amount * 2
price = 100
discount = 20
price /= (100 - discount) / 100 # Equivalent to price = price / ((100 - discount) / 100)
//= operator
The //=
operator is used to perform integer division and assign the result to the variable.
number = 25
number //= 4 # Equivalent to number = number // 4, the result is 6
After this operation, number
will be equal to 6
.
%= and **= operators
These operators are used to calculate the modulus (%=
) and the power (**=
) of the variable and assign the result to the variable, respectively.
number = 10
number %= 3 # Equivalent to number = number % 3
base = 2
exponent = 3
base **= exponent # Equivalent to base = base ** exponent
%= and **= operators
These operators are used to calculate the modulus (%=
) and the power (**=
) of the variable and assign the result to the variable, respectively.
number = 10
number %= 3 # Equivalent to number = number % 3
base = 2
exponent = 3
base **= exponent # Equivalent to base = base ** exponent