Python模量
示例
像许多其他语言一样,Python使用%运算符来计算模数。
3 % 4 #3 10 % 2 #0 6 % 4 #2
或通过使用operator模块:
import operator operator.mod(3 , 4) #3 operator.mod(10 , 2) #0 operator.mod(6 , 4) #2
您也可以使用负数。
-9 % 7 #5 9 % -7 #-5 -9 % -7 #-2
如果需要查找整数除法和模数的结果,可以将该divmod函数用作快捷方式:
quotient, remainder = divmod(9, 4) #商=2,余数=1为4*2+1==9