像这样的表情x % y计算为x ÷ y..优先级与运算符相同。/(分组)及*(乘法)
>>> 9 / 2
4
>>> 9 % 2
1
9除以2等于4。
4乘2等于8
9减8是1-剩余部分。
Python抓到了:取决于您使用的Python版本,%也是(不推荐的)字符串内插运算符,因此请注意,如果您来自具有自动类型转换(如PHP或JS)的语言,其中的表达式如下'12' % 2 + 3是合法的:在Python中,它将导致TypeError: not all arguments converted during string formatting这可能会让你很困惑。
[Python 3更新]
用户n00p注释:
9/2在python中是4.5。如果您想让python告诉您除法(4)之后还剩下多少个完整的对象,那么就必须进行整数除法:9/2。
确切地说,整数除法在Python 2中是默认的(请注意,这个答案比我已经在学校的孩子要老):
$ python2.7
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4
>>> 9 // 2
4
>>> 9 % 2
1
在Python 3中9 / 2结果4.5的确如此,但请记住,最初的答案是非常古老的。
$ python3.6
Python 3.6.1 (default, Apr 27 2017, 00:15:59)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4.5
>>> 9 // 2
4
>>> 9 % 2
1