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

前端 未结 9 653
梦谈多话
梦谈多话 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:52

    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.

    0 讨论(0)
  • 2021-01-23 07:53

    the -= is an operator, what you wrote will produce num = num - 1.

    0 讨论(0)
  • 2021-01-23 07:54
    num -= 1
    

    is the same as

    num = num - 1
    
    0 讨论(0)
  • 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.

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

    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.

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

    -= 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.

    0 讨论(0)
提交回复
热议问题