4.2 Assignment operators
4.2a What are assignment operators?
Assignment operators in Python are used to change the value of a variable. They combine a basic math operation (like addition or multiplication) with assigning a new value to the variable. They make your code shorter and easier to read.
4.2b Why use these assignment operators?
- Convenience - They make your code shorter and easier to write.
- Readability - They make it clear that you are updating the value of a variable.
4.2c Main assignment operators
The main assignment operators that we will use in this course are:
|
|
+=
(Add and Assign)
This operator adds a number to the current value of a variable and then assigns the new value to that variable.
Example 4.2.1
Example 4.2.1 - Output8
-=
(Subtract and Assign)
This operator subtracts a number from the current value of a variable and then assigns the new value to that variable.
Example 4.2.2
Example 4.2.2 - Output
3
*=
(Multiply and Assign)
This operator multiplies the current value of a variable by a number and then assigns the new value to that variable.
Example 4.2.3
Example 4.2.3 - Output
20
/=
(Divide and Assign)
This operator divides the current value of a variable by a number and then assigns the new value to that variable.
Example 4.2.4
Example 4.2.4 - Output
5.0 # Note the decimal
//=
(Floor Divide and Assign)
This operator divides the current value of a variable by a number, rounds down to the nearest whole number, and then assigns the new value to that variable.
Example 4.2.5
Example 4.2.5 - Output
3
%=
(Modulus and Assign)
This operator calculates the remainder when the current value of a variable is divided by a number and then assigns the new value (the remainder) to that variable.
Example 4.2.6
Example 4.2.6 - Output
1
4.2d Interpret a program snippet that includes assignment operators.
Example 4.2.7 - In this example, you can see how each assignment operator changes the value of x step by step.
x = 10 # Start with x equal to 10
x += 5 # Add 5 to x, now x is 15
x -= 3 # Subtract 3 from x, now x is 12
x *= 2 # Multiply x by 2, now x is 24
x /= 4 # Divide x by 4, now x is 6.0
x //= 2 # Floor divide x by 2, now x is 3
x %= 2 # Get the remainder of x divided by 2, now x is 1
print(x)
Example 4.2.7 - Output
1.0
4.2e Develop a program using assignment operators.
Exercise 4.2.1 - Write a Python program that starts with a variable score set to 100. Perform the following operations on score using assignment operators and print the result after each operation:
- Decrease score by 15 using
-=
. - Increase score by 20 using
+=
. - Multiply score by 3 using
*=
. - Divide score by 2 using
/=
. - Floor divide score by 5 using
//=
. - Take the remainder of score divided by 4 using
%=
.
Exercise 4.2.1 - Model Answer - Make sure to work out the exercise before checking the model answer.