In line 4 why do we have to add \"=\" after \"-\" ?
num = 5
if num > 2:
print(num)
num -= 1
print(num)
The =
is needed to assign the result of the subtraction back to num
.
The following:
num -= 1
subtracts one from num
and assigns the result back to num
.
On the other hand, the following:
num - 1
subtracts one from num
and discards the result.
the -=
is an operator, what you wrote will produce num = num - 1
.
num -= 1
is the same as
num = num - 1
num - 1
: produce the result of subtracting one from num
; num
is not changed
num -= 1
: subtract one from num
and store that result (equivalent to num = num - 1
when num
is a number)
Note that you can use num - 1
as an expression since it produces a result, e.g. foo = num - 1
, or print(num - 1)
, but you cannot use num -= 1
as an expression in Python.
You do not have to do anything, unless you are required to do something for your program to run correctly. Some things are good practice, but don't let anyone or anything but the compiler and the specification convince you that you have to do something one way or another. In this case, n -= 1
is exactly the same as n = n - 1
. Therefore, if you do not wish to put the -
before the =
, then don't. Use n = n - 1
instead.
-=
is an operator.
This operator is equals to subtraction.
num -= 1
means is num = num - 1
It is used to subtraction from the itself with given value in right side.