Python divmod() 函式



**Python divmod() 函式**接受兩個數字作為引數值,並返回一個包含兩個值的元組,即它們的商和餘數。

如果我們向**divmod()**函式傳遞非數字引數(例如字串),則會遇到TypeError;如果將0作為第二個引數傳遞,則會返回ZeroDivisionError。

**divmod()**函式是內建函式之一,不需要匯入任何模組。

語法

以下是 python **divmod()** 函式的語法。

divmod(dividend, divisor)

引數

Python **divmod()** 函式接受兩個引數,如下所示:

  • **被除數** - 此引數指定要被除的數。

  • **除數** - 此引數表示被除數將被除以的數。

返回值

python **divmod()** 函式返回商和餘數,作為一個元組

divmod() 函式示例

練習以下示例以瞭解如何在 Python 中使用**divmod()**函式

示例:divmod() 函式的使用

以下是一個 Python divmod() 函式的示例。在這裡,我們將兩個整數作為引數傳遞給 divmod() 函式,它將返回一個包含它們的商和餘數的元組。

output = divmod(18, 5)
print("The output after evaluation:", output)

執行上述程式後,將生成以下輸出:

The output after evaluation: (3, 3)

示例:帶有負值的 divmod()

如果我們將負數傳遞給 divmod() 函式,它將返回商的地板值和餘數,如下面的程式碼所示。

output = divmod(-18, 5)
print("The output after evaluation:", output)

執行上述程式後,將獲得以下輸出:

The output after evaluation: (-4, 2)

示例:帶有浮點值的 divmod()

Python 的 **divmod()** 函式也相容浮點數。在下面的例子中,我們將浮點值作為引數傳遞給此函式,它將返回浮點型別的結果。

output = divmod(18.5, 5)
print("The output after evaluation:", output)

執行上述程式後,得到以下輸出:

The output after evaluation: (3.0, 3.5)

示例:divmod() 函式的除零錯誤

當 divmod() 的第二個引數為 0 時,它將引發 ZeroDivisionError。在下面的程式碼中,我們將 0 作為除數,因此得到 ZeroDivisionError。

try:
   print(divmod(27, 0))
except ZeroDivisionError:
   print("Error! dividing by zero?")

執行上述程式後,顯示以下輸出:

Error! dividing by zero?

示例:將秒轉換為小時、分鐘和秒

在下面的程式碼中,我們演示了 Python 中 divmod() 函式的一個實際應用。在這裡,我們將秒轉換為小時和分鐘。

secValue = 8762
hours, remainingSec = divmod(secValue, 3600)
minutes, seconds = divmod(remainingSec, 60)
print("The total time after evaluating seconds:")
print(f"{hours} hours, {minutes} minutes, {seconds} seconds"))

執行上述程式後,顯示以下輸出:

The total time after evaluating seconds:
2 hours, 26 minutes, 2 seconds
python_built_in_functions.htm
廣告