更新時(shí)間:2023-07-17 來(lái)源:黑馬程序員 瀏覽量:
IT就到黑馬程序員.gif)
在Python中,divmod()函數(shù)是一個(gè)內(nèi)置函數(shù),用于執(zhí)行整數(shù)除法并返回商和余數(shù)。它接受兩個(gè)參數(shù),被除數(shù)和除數(shù),并返回一個(gè)包含商和余數(shù)的元組。divmod()函數(shù)可以方便地在執(zhí)行除法時(shí)同時(shí)獲取商和余數(shù)。
以下是divmod()函數(shù)的用法示例:
# 示例 1
result = divmod(10, 3)
print(result) # 輸出 (3, 1)
# 示例 2
quotient, remainder = divmod(15, 4)
print(quotient) # 輸出 3
print(remainder) # 輸出 3
# 示例 3
numerator = 23
denominator = 6
quotient, remainder = divmod(numerator, denominator)
print(f"The quotient is {quotient} and the remainder is {remainder}") # 輸出 "The quotient is 3 and the remainder is 5"在示例1中,divmod(10, 3)執(zhí)行整數(shù)除法10 // 3并返回商3和余數(shù)1的元組。
在示例2中,divmod(15, 4)執(zhí)行整數(shù)除法15 // 4并將商和余數(shù)分別賦值給quotient和remainder兩個(gè)變量。
在示例3中,divmod(numerator, denominator)執(zhí)行了變量numerator和denominator的整數(shù)除法,并將商和余數(shù)分別賦值給quotient和remainder兩個(gè)變量。最后,使用格式化字符串輸出商和余數(shù)的值。
總結(jié):divmod()函數(shù)的作用是執(zhí)行整數(shù)除法并返回商和余數(shù)的元組,它可以用于各種需要同時(shí)獲取商和余數(shù)的場(chǎng)景。