I’m writing a script which calculates the date of Easter for years 1900 – 2099.
The thing is that for 4 certain years (1954, 1981, 2049, and 2076) the formula differs a little bet (namely, the date is off 7 days).
def main():
print "Computes the date of Easter for years 1900-2099.\n"
year = input("The year: ")
if year >= 1900 and year <= 2099:
if year != 2049 != 2076 !=1981 != 1954:
a = year%19
b = year%4
c = year%7
d = (19*a+24)%30
e = (2*b+4*c+6*d+5)%7
date = 22 + d + e # March 22 is the starting date
if date <= 31:
print "The date of Easter is March", date
else:
print "The date of Easter is April", date - 31
else:
if date <= 31:
print "The date of Easter is March", date - 7
else:
print "The date of Easter is April", date - 31 - 7
else:
print "The year is out of range."
main()
Exerything is working well but the 4 years computation.
I’m getting the:
if date <= 31: whenever I’m entering any of the 4 years as input.
UnboundLocalError: local variable 'date' referenced before assignment
You cannot chain a expression like that; chain the tests using
andoperators or use anot inexpression instead:The expression
year != 2049 != 2076 !=1981 != 1954means something different, it is interpreted as(((year != 2049) != 2076) !=1981) != 1954instead; the first test is eitherTrueorFalse, and neither of those two values will ever be equal to any of the other numbers and that branch will always evaluate toFalse.You will still get the
UnboundLocalErrorfordatethough, since yourelsebranch refers todatebut it is never set in that branch. When theelsebranch executes, all Python sees is:and
dateis never assigned a value in that case. You need to calculatedateseparately in that branch still, or move the calculation of thedatevalue out of theifstatement altogether; I am not familiar with the calculation of Easter so I don’t know what you need to do in this case.