Python 閏年檢查器
使用 Python 中的標準整除性檢查確定一年是否為閏年。
概述
閏年包含 366 天,而不是 365 天,二月又增加了一天。它的發生是為了使日曆年與天文年保持同步。
該規則規定,如果年份能被 4 整除,則該年份為閏年,但世紀年(以 00 結尾的年份)除外,它也必須能被 400 整除。
此計算在 Python 中使用組合邏輯運算子(“and”、“or”)和模運算子來實現。
程式碼和執行輸出
基於整除性的演算法來驗證多個測試年份,包括世紀年。
leap_year.py
在編輯器中嘗試def is_leap_year(year):
# A year is leap if it is divisible by 4
# and (not divisible by 100 or divisible by 400)
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
years = [2000, 2004, 1900, 2023, 2024]
for y in years:
status = "Leap Year" if is_leap_year(y) else "Not a Leap Year"
print(f"Year {y}: {status}")端子輸出
Year 2000: Leap Year
Year 2004: Leap Year
Year 1900: Not a Leap Year
Year 2023: Not a Leap Year
Year 2024: Leap Year逐步實施
- 計劃、日曆和日期時間模組驗證
- 準確確定年齡或日期差異
- 財務及利息計算公式
常見問題解答
為什麼 1900 年不是閏年?
儘管 1900 年可以被 4 整除,但它以 00(世紀年)結束,因此必須能被 400 整除才是閏年。由於 1900 / 400 不是整數,因此不是閏年。