Other than the = sign, there are more assignment operators in Python (and other programming languages). This includes operators like +=, -= and *=.
Let us take a variable x with an initial value of 10. If we want to increment x by 2 , we do
x = x + 2
The program will evaluate the expression on the right and assign it to the variable in the left. Therefore, the statement will eventually become x ← 12.
Instead of writing x = x + 2, we can do x +=2. The += combines the assignment sign with the addition operator. So, x +=2 is the same as x = x + 2.
Similarly, if we want to subtract, we can write x = x - 2 or x -= 2. We can also multiply by writing x = x*2 or x *=2.
No comments:
Post a Comment