Home >Backend Development >Python Tutorial >What Correction is Needed to Make a Python Function Determine Leap Years Correctly?
Determining Leap Years
You're attempting to write a program to ascertain if a specific year qualifies as a leap year. However, your current code returns "None" when executed in Python IDLE.
Recall that a leap year meets the following criteria:
Examining your code:
<code class="python">def leapyr(n): if n%4==0 and n%100!=0: if n%400==0: print(n, "is a leap year.") elif n%4!=0: print(n, "is not a leap year.") print(leapyr(1900))</code>
The issue lies in the last line: print(leapyr(1900)). When you call a function returning no value (such as leapyr in this case), the return value is always None. To resolve this, you can directly print the result within the function itself:
<code class="python">def leapyr(n): if n%4==0 and n%100!=0: if n%400==0: return n, "is a leap year." elif n%4!=0: return n, "is not a leap year." result = leapyr(1900) print(result)</code>
An Alternative Approach Using calendar.isleap
Python provides a built-in function named calendar.isleap that explicitly determines whether a given year is a leap year:
<code class="python">import calendar print(calendar.isleap(1900))</code>
This function simplifies the task and returns a straightforward Boolean value.
The above is the detailed content of What Correction is Needed to Make a Python Function Determine Leap Years Correctly?. For more information, please follow other related articles on the PHP Chinese website!