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

前端 未结 9 655
梦谈多话
梦谈多话 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 08:07

    Because num - 1 does nothing, but num -= 1 changes the value of num by minus one.

    0 讨论(0)
  • 2021-01-23 08:09

    You are essentially asking the difference between

    num - 1
    

    and

    num -= 1
    

    The former is an expression that evaluates to num - 1. The latter is an assignment that assigns num - 1 to num.

    So, the former does not modify num, the latter does.

    0 讨论(0)
  • 2021-01-23 08:14

    It's a shorter version of writing:

    num = num - 1
    
    0 讨论(0)
提交回复
热议问题