简体   繁体   中英

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

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

num = 5
if num > 2:
    print(num)
    num -= 1
print(num)

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, eg foo = num - 1 , or print(num - 1) , but you cannot use num -= 1 as an expression in Python.

num -= 1

是相同的

num = num - 1

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 .

因为num - 1不执行任何操作,但是num -= 1会将num的值减一。

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.

这是写作的简短版本:

num = num - 1

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.

-=是一个运算符,您编写的将产生num = num - 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM