%在计算中是什么?我不知道它是做什么的。

它能算出计算的百分比吗例如4% 2显然等于0。如何?


当前回答

请注意

(3 +2 + 1 - 5) + (4 % 2) - (1/4) + 6

即使使用括号,在Python 3.4中计算的结果也是6.75,而不是7。


'/'操作符也不是那么容易理解(python2.7): try…

- 1/4

1 - 1/4

这有点离题,但在计算上面的表达式时应该考虑:)

其他回答

%(取模)操作符产生第一个参数除以第二个参数的余数。数值参数首先转换为公共类型。

3 + 2 + 1-5 + 4% 2-1/4 + 6 = 7

这基于运算符优先级。

模运算符也可以用于打印字符串(就像在C中一样),定义在谷歌https://developers.google.com/edu/python/strings上。

      # % operator
  text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')

这似乎有点离题,但它肯定会帮助到某人。

有点偏离主题,%也用于字符串格式化操作,如%=,将值替换为字符串:

>>> x = 'abc_%(key)s_'
>>> x %= {'key':'value'}
>>> x 
'abc_value_'

同样,跑题了,但它似乎是一个小小的文档特性,我花了一段时间才找到,我认为它与python模数计算有关,这个SO页面在这方面排名很高。

此外,还有一个有用的内置函数divmod:

divmod (a, b) 取两个(非复数)数字作为参数并返回一对数字 由它们的商和组成 使用长除法时的余数。

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

摘自http://docs.python.org/reference/expressions.html

示例1: 6%2的结果为0,因为如果6除以2,没有余数(3倍)。

例2:7%2的结果是1,因为当7除以2(3次)时,余数是1。

总结一下,它返回除法运算的余数,如果没有余数,则返回0。6%2意味着6的余数除以2。