Home  >  Article  >  Backend Development  >  What Correction is Needed to Make a Python Function Determine Leap Years Correctly?

What Correction is Needed to Make a Python Function Determine Leap Years Correctly?

Linda Hamilton
Linda HamiltonOriginal
2024-10-21 18:52:03701browse

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:

  • Divisible by 4
  • Not divisible by 100 (exception: divisible by 400)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn