1. 使用求模运算符 `%`:
num = 21
if num % 2 == 0:
print("The number " + str(num) + " is even.")
else:
print("The number " + str(num) + " is odd.")
2. 使用 `divmod()` 函数:
num, remainder = divmod(10, 3)
print("The quotient is " + str(num) + " and the remainder is " + str(remainder))
3. 使用 `//` 运算符进行整除,然后通过减法计算余数:
num = 21
quotient = num // 2
remainder = num - quotient * 2
print("The quotient is " + str(quotient) + " and the remainder is " + str(remainder))
num = -21
remainder = num % 3 结果为 -1,因为 -21 % 3 等于 -1
print("The remainder is " + str(remainder))
以上是Python中取余操作的基本方法。