If statement 决策树Python与异常2.7

If statement 决策树Python与异常2.7,if-statement,python-2.7,If Statement,Python 2.7,我正在写一个脚本,计算1900-2099年复活节的日期。 问题是,在特定的4年(1954年、1981年、2049年和2076年)中,公式有一点不同(即日期为7天) def main(): print“计算1900-2099年的复活节日期。\n” 年份=输入(“年份:”) 如果年份>=1900且年份则无法链接这样的表达式;使用和运算符链接测试,或使用不在表达式中: # and operators if year != 2049 and year != 2076 and year != 1981 a

我正在写一个脚本,计算1900-2099年复活节的日期。 问题是,在特定的4年(1954年、1981年、2049年和2076年)中,公式有一点不同(即日期为7天)

def main():
print“计算1900-2099年的复活节日期。\n”
年份=输入(“年份:”)

如果年份>=1900且年份则无法链接这样的表达式;使用
运算符链接测试,或使用
不在
表达式中:

# and operators
if year != 2049 and year != 2076 and year != 1981 and year != 1954:

# not in expression
if year not in (2049, 2076, 1981, 1954):
表达式
year!=2049 != 2076 !=1981 != 1954年
的意思有所不同,它被解释为
((年份!=2049)!=2076)!=1981)!=1954年
;第一个测试是
True
False
,这两个值都不会等于任何其他数字,并且该分支将始终计算为
False

尽管如此,您仍然会得到
date
UnboundLocalError
,因为您的
else
分支引用了
date
,但它从未在该分支中设置。当执行
else
分支时,Python看到的所有内容都是:

def main():
    print "Computes the date of Easter for years 1900-2099.\n"

    year = input("The year: ")

    if year >= 1900 and year <= 2099:
        if False:    
            # skipped
        else: 
            if date <= 31:
                print "The date of Easter is March", date - 7 
            else:
                print "The date of Easter is April", date - 31 - 7
def main():
print“计算1900-2099年的复活节日期。\n”
年份=输入(“年份:”)

如果年份>=1900,如果我正确阅读代码,那么需要做的就是将
a=
行移到
date=
行左侧一级,然后将
if year not in
行移到
date=
行下方。您用最后一个代码@Martijn揭示了本地错误,对此我再次表示感谢。您在@DSM处完美地阅读了代码,它起了作用!!!谢谢我欠你们很多人情。
def main():
    print "Computes the date of Easter for years 1900-2099.\n"

    year = input("The year: ")

    if year >= 1900 and year <= 2099:
        if False:    
            # skipped
        else: 
            if date <= 31:
                print "The date of Easter is March", date - 7 
            else:
                print "The date of Easter is April", date - 31 - 7