Assignment operators allow us to assign values to variables.
If you want to learn more
consult the Introduction to Programming Course read more
List of assignment operators
Operator =
The assignment operator (=
) is used to assign a value to a variable.
number = 10
In this example, number
is a variable to which the value 10
is assigned.
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
.
Operators *=
and /=
These operators are used to multiply (*=
) and divide (/=
) the variable by the value on the right and assign the result to the variable, respectively.
quantity = 5
quantity *= 2 # Equivalent to quantity = quantity * 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
.
Operators %=
and **=
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