W WolfCode · CSC 141

Leap Year

闰年判断

≈ 15 min · python-conditionals · Open in WolfCode

The textbook's 'flatten the nested if' lesson with a real-world rule. Three levels deep becomes one Boolean expression.

The Gregorian rule

A year is a leap year if it is divisible by 4, EXCEPT years divisible by 100 are NOT leap, EXCEPT years divisible by 400 ARE leap.

The nested approach (don't do this)

Works, but hard to read and easy to mess up

The flat approach (do this)

Python · runnable

Read it aloud: "Divisible by 4 AND not by 100 — OR — divisible by 400."

Trace 1900 by hand

  • 1900 % 4 == 0True
  • 1900 % 100 != 0False
  • (True and False)False
  • 1900 % 400 == 0False
  • (False) or (False)False

Check yourself

Pretend you're Python. Evaluate both clauses separately.

What about year 2100?

Now you try

Open 03-leap-year.py and implement is_leap_year as a single return. The autograder runs 6 tests including all three branches of the rule.