-1

This is the question: Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False.

This is the background information about leap years:

The year can be evenly divided by 4, is a leap year, unless:

The year can be evenly divided by 100, it is NOT a leap year, unless:

The year is also evenly divisible by 400. Then it is a leap year.

The code for this is:

def is_leap(year):
    
    return year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)

Im struggling to understand how the and and or statements work together to solve this question.

Craicerjack
  • 6,203
  • 2
  • 31
  • 39
andz
  • 3
  • 1
  • 1
    This is less a Python question and more a question about how the above criteria for leap years translates to "A year is a leap year if it is evenly divisible by 4 and is either evenly divisible by 400 or *not* evenly divisible by 100." – jjramsey Jul 20 '22 at 13:25
  • 1
    Read more here https://docs.python.org/3/reference/expressions.html#operator-precedence or https://stackoverflow.com/questions/16679272/priority-of-the-logical-operators-not-and-or-in-python – noah1400 Jul 20 '22 at 13:27

1 Answers1

0

Whenever you have value % something == 0, that statement will return true if and only if value is divisible by something, as one way to define divisibility is that you get a 0 remainder when dividing.

So breaking down the logic, we have return (year is divisible by 4) and ((year is divisible by 400) or (year is not divisible by 100)).

The and operator means that both things must be true in order for the output to be true. So, we have

  1. The year is divisible by 4
  2. (The year is divisible by 400) OR (The year is not divisible by 100)

These must both be True for the output to be True. If even one is False, then the output is False.

The first condition is very intuitive -- only years divisible by 4 can be leap years, so we can automatically remove any other years. Again, BOTH must be True for the output to be true, so even one wrong will cause the output to be False.

Now, let's look at the second condition: since it uses or, just one of those two has to be correct. If the year IS divisible by 100, then the second part of the second condition will be false, as that says that the year must NOT be divisible by 100. This addresses the second part of your prompt: "If the year can be evenly divided by 100, it is NOT a leap year".

However, we still have to consider the third part of the prompt: if the year is divisible by 400, it's still a leap year. That's what the first part of the second prompt does. Even in cases where year IS divisible by 100, making the second part of the second condition False, the first part of the second condition will be True when year is divisible by 400, and since only one of them needs to be True, this makes the entire second condition True.

linger1109
  • 500
  • 2
  • 11