Ad

How Are The & And | Operators Evaluated In If Statements Without Parentheses?

- 1 answer

I am doing a practice course for Python that requests a script to calculate leap years.

Leap years have the following conditions:

  • Must be a multiple of 4
  • Must NOT be a multiple of 100, unless it is also a multiple of 400.

Attempt1

year = int(input("Check this year "))

leapFourYears = year % 4
leapCentury = year % 100
leapFourCenturies = year % 400

if (leapFourYears == 0 & leapCentury != 0) | leapFourCenturies == 0:
    print('leap year')
else:
    print('not leap year')

This works for, e.g., 2000, but it incorrectly prints 'not leap year' for, e.g., 2016.

I printed out each condition, and individually, they evaluate to true or false as expected. However, the moment I involve a & or | operator, the evaluation goes awry.

I started attaching parentheses and came upon this correct if-statement:

Attempt 2

if ((leapFourYears == 0) & (leapCentury != 0)) | (leapFourCenturies == 0):

This works.

Can someone explain to me how Python python parses multiple conditions with & and | operators that do not have parentheses? How is Python evaluating it that makes it work for 2000 but not 2016?

Is there a way to do this without the parentheses around each condition?

Thanks!

Python 3.8.10

Ad

Answer

You are using the bitwise operators, not the logical operators. Instead of

if ((leapFourYears == 0) & (leapCentury != 0)) | (leapFourCenturies == 0):

use

if leapFourYears == 0 and leapCentury != 0 or leapFourCenturies == 0:

The and has priority over or.

Ad
source: stackoverflow.com
Ad