What does the “variable //= a value” syntax mean in Python? [duplicate]

自作多情 提交于 2019-12-08 17:00:14

问题


I came across with the code syntax d //= 2 where d is a variable. This is not a part of any loop, I don't quite get the expression.
Can anybody enlighten me please?


回答1:


// is a floor division operator. The = beside it means to operate on the variable "in-place". It's similar to the += and *= operators, if you've seen those before, except for this is with division.

Suppose I have a variable called d. I set it's value to 65, like this.

>>> d = 65

Calling d //= 2 will divide d by 2, and then assign that result to d. Since, d // 2 is 32 (32.5, but with the decimal part taken off), d becomes 32:

>>> d //= 2
>>> d
32

It's the same as calling d = d // 2.




回答2:


It divides d by 2, rounding down. Python can be run interactively, Try it.

$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
>>> a = 4
>>> a //= 2
>>> a
2



回答3:


Divides the variable with floor division by two and assigns the new amount to the variable.



来源:https://stackoverflow.com/questions/40274205/what-does-the-variable-a-value-syntax-mean-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!