如何在Python中找到一个数的除法余数呢?

例如: 如果这个数是26,整除数是7,那么整除余数是5。 (因为7+7+7=21,26-21=5。)


有关简单的可整除性测试,请参见如何检查一个数是否能被另一个数整除。


当前回答

如果你想在一行代码中得到商和余数(更通用的情况),使用:

quotient, remainder = divmod(dividend, divisor)
#or
divmod(26, 7)

其他回答

26 % 7(你将得到余数)

26 / 7(你会得到除数,可以是浮点值)

26 // 7(你将得到除数,只有整数值)

除法的余数可以使用运算符%来发现:

>>> 26%7
5

如果你同时需要商和模,有一个内置的divmod函数:

>>> seconds= 137
>>> minutes, seconds= divmod(seconds, 60)

如果你想在一行代码中得到商和余数(更通用的情况),使用:

quotient, remainder = divmod(dividend, divisor)
#or
divmod(26, 7)

您可以定义一个函数,并将其称为具有2个值的remainder,如rem(number1,number2),返回number1%number2 然后创建一个while,并将其设为true然后为持有编号1和2的函数输出两个输入然后输出(rem(number1,number2)

除法时用%代替/。这将为您返回余数。所以在你的案例中

26 % 7 = 5