Tutorial Study Image

Python divmod()

在 Python 中,divmod 函数接受两个数字作为参数,用第一个数除以第二个数,然后返回商和余数的元组。


divmod(dividend,divisor) #The dividend will be divided by 

divmod() 参数

该函数接受两个必需参数,第一个参数被视为被除数,第二个参数被视为除数。第二个参数不能为零,因为

参数 描述 必需/可选
被除数 将被除的数字 必需
除数 用于除的数字。该数字不能为零。 必需

divmod() 返回值

该函数始终根据输入返回一个包含商和余数的元组。两个参数都是必需的。

输入 返回值
被除数和除数 一个包含商和余数的元组
字符串作为第一个参数,编码作为第二个参数。 将字符串编码为字节。
可迭代对象 字节大小与可迭代对象相同
无参数 创建一个没有元素的字节对象

Python 中 divmod() 方法的示例

示例 1:传入一个整数作为参数


result = divmod(2,1)
print(“Divmod of 2 and 1 are :”, result)
result = divmod(3.5,2.5)
print(“Divmod of 3.5 and 2.5 are :”, result)
 

输出

Divmod of 2 and 1 are : (2, 0)
Divmod of 3.5 and 2.5 are : (1.0, 1.0)

示例 2:传入一个浮点数作为参数


print('divmod(8.0, 3) = ', divmod(8.0, 3))
print('divmod(3, 8.0) = ', divmod(3, 8.0))
print('divmod(7.5, 2.5) = ', divmod(7.5, 2.5))
print('divmod(2.6, 0.5) = ', divmod(2.6, 0.5))
 

输出


divmod(8.0, 3) =  (2.0, 2.0)
divmod(3, 8.0) =  (0.0, 3.0)
divmod(7.5, 2.5) =  (3.0, 0.0)
divmod(2.6, 0.5) =  (5.0, 0.10000000000000009)