Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。
divmod():同時算商和餘數
語法:
divmod(a, b)一次回傳 (商, 餘數) 的 tuple,等於同時做 a // b 和 a % b:print(divmod(10, 3)) # (3, 1) → 10 ÷ 3 = 商 3 餘 1
print(divmod(17, 5)) # (3, 2) → 17 ÷ 5 = 商 3 餘 2
print(divmod(20, 4)) # (5, 0) → 剛好整除也可以用在浮點數上:
print(divmod(7.5, 2)) # (3.0, 1.5)小小綜合例子
# 把秒數轉成「幾分幾秒」
total_seconds = 150
minutes, seconds = divmod(total_seconds, 60)
print(f"{total_seconds} 秒 = {minutes} 分 {seconds} 秒") # 150 秒 = 2 分 30 秒