course content

Course Content

Conditional Statements in Python

Logical Operators 2/2Logical Operators 2/2

Python has priorities in which order the operations are performed. You must use parentheses to change the order of calculations.

However, if you do not use parentheses, the priorities in the operators are as follows:

Example

The precedence among logical operators:

Example

Let's clarify this with example:

In the code above, you can clearly see that these expressions differ only due to the presence of parentheses, resulting in completely contrasting outcomes. Now, let's delve into the reasoning behind this phenomenon.

In the first expression, due to the higher precedence of the and operation over the or operation, the conditions Dog and Lizard are evaluated. The result becomes Lizard. Then, we proceed to the or part: Cat or Lizard. In this case, the overall result becomes Cat because the or statement chooses the first non-false statement.

However, in the second expression, the first operation executed is inside the parenthesis: Cat or Dog. Here, the or operation returns the first non-false value, which is Cat. As a result, the final operation with the and operator becomes Cat and Lizard, leading to the ultimate result of Lizard, as the and operator selects the second value in this scenario.

Task

Create a program that checks whether a given year is a leap year. A leap year is divisible by 4 but not divisible by 100, except if it's also divisible by 400. The program should output either 'Leap year' or 'Not a leap year' accordingly.

  1. The main condition of the leap year is that year must be divided by 4. Use year % 4 == 0;
  2. The second condition is that the year must not be divided by 100. Use year % 100 != 0;
  3. But if the year is divisible by 400 is the leap year. Use year % 400 == 0.

Everything was clear?

Section 1. Chapter 6
toggle bottom row