Python中取余運算使用百分號 %,其核心規(guī)則是:余數(shù)符號與除數(shù)一致。計算時先執(zhí)行向下取整的除法(a // b),再通過公式 a % b = a - (a // b) * b 得到結(jié)果。例如 10 % 3 返回 1,而 -10 % 3 返回 2。此規(guī)則適用于整數(shù)和浮點數(shù),但需避免除數(shù)為零,跟著小編一起詳細(xì)了解下。
1. 取余符號
python1remainder = a % b # 計算a除以b的余數(shù)
2. 運算規(guī)則
Python的取余運算滿足以下公式:
a % b = a - (a // b) * b
其中 // 是向下取整的除法(即結(jié)果向負(fù)無窮方向取整)。
關(guān)鍵特性:
結(jié)果符號與除數(shù) b 一致
無論被除數(shù) a 是正是負(fù),余數(shù)的符號始終與 b 相同。
例如:
python1print(10 % 3) # 輸出: 1 (10 ÷ 3 = 3余1)
2print(-10 % 3) # 輸出: 2 (因為 -10 ÷ 3 = -4余2,符號與3一致)
3print(10 % -3) # 輸出: -2 (10 ÷ -3 = -4余-2,符號與-3一致)
浮點數(shù)同樣適用
python1print(10.5 % 3) # 輸出: 1.5 (10.5 ÷ 3 = 3.5余1.5)
與 divmod() 函數(shù)的關(guān)系
divmod(a, b) 返回 (a // b, a % b) 的元組:
python1quotient, remainder = divmod(10, 3)
2print(quotient, remainder) # 輸出: 3 1

3. 示例對比
表達(dá)式計算過程結(jié)果
10 % 310 - (10 // 3)*3 = 10 - 91
-10 % 3-10 - (-10 // 3)*3 = -10 - (-12)2
10 % -310 - (10 // -3)*-3 = 10 - (-9)-2
4. 應(yīng)用場景
判斷奇偶性
python1if num % 2 == 0:
2 print("偶數(shù)")
循環(huán)索引(如環(huán)形緩沖區(qū))
python1index = current_index % buffer_size
時間轉(zhuǎn)換(如秒數(shù)轉(zhuǎn)時分秒)
python1seconds = 3665
2minutes = seconds // 60
3remaining_seconds = seconds % 60 # 輸出: 5
5. 注意事項
除數(shù) b 不能為0,否則會觸發(fā) ZeroDivisionError。
若需嚴(yán)格數(shù)學(xué)模運算(結(jié)果非負(fù)),可手動調(diào)整:
python1def math_mod(a, b):
2 return ((a % b) + b) % b
3print(math_mod(-10, 3)) # 輸出: 2(始終非負(fù))
python中的取余運算其實就是取模運算,通過理解 % 的運算規(guī)則,可以避免因符號問題導(dǎo)致的邏輯錯誤,尤其在處理負(fù)數(shù)或循環(huán)問題時。通過理解 % 的底層邏輯,可更靈活處理邊界情況,避免常見陷阱。