“num - 1” vs “num -= 1”

前端 未结 9 669
梦谈多话
梦谈多话 2021-01-23 07:18

In line 4 why do we have to add \"=\" after \"-\" ?

num = 5
if num > 2:
    print(num)
    num -= 1
print(num)
9条回答
  •  攒了一身酷
    2021-01-23 07:58

    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.

提交回复
热议问题